【4858美高梅】的办法库整理,js对象数组深度去重和纵深排序

By admin in 4858美高梅 on 2019年4月14日

4858美高梅 1

collect.js 是
javascript的3个卷入库,用于拍卖array和object,能够用它轻松得建立二个map也许修改现有的,可惜它的方法名实在有点难懂,尤其是对大家那些英文不是母语的人来说,所以就想把它整理一下,现在能够查找。

一.数组中已存在七个可直接用来重排序的不2法门:reverse()和sort()。

JavaScript中的Array对象有和好的排序方法sort(),对数组中的数据项进行排序,然而有时排序结果不顺遂,比如

 

collect.js 的 github:
https://github.com/ecrmnn/collect.js

reverse()和sort()方法的再次回到值是因此排序后的数组。reverse()方法会反转数组项的依次:

var arr = [12, 1, 2, 21, 3];
arr.sort();
alert(arr);   得到的结果为 1,12,2,21,3

采纳collect.js处理数组和指标

上面就按成效来分类:

var values=[1,2,3,4,5];
values.reverse();
alert(values); //5,4,3,2,1

那是为啥呢?因为JavaScript中的排序暗许遵照ascii字符代码进行排序,相当于说,数字也是比照它们的字符串情势排序的。

https://github.com/ecrmnn/collect.js/\#

  • 取出集合中的一片段
  • 分隔
  • 用来组合集合
  • 用于操作集合内的
  • 遍历
  • 看清集合的有效性
  • 过滤
  • 只操作对象和关联数组
  • 排序
  • 输出

在暗中认可情况下,sort()方法按升序排列数组,sort()方法会调用各种数组项的toString()转型措施,然后相比获得字符串,鲜明什么排序。即便数组中的每壹项都以数值,sort()方法相比的也是字符串:

var strArr = ['a', '2', 'a2', '2a', 'b', '3'];
alert(strArr.sort());

 

用来取出集合中的一片段

  • all() 取出全数

collect([1, 2, 3]).all();

//=> [1, 2, 3]
  • forPage() 分页再次来到集合的一有的

const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

const forPage = collection.forPage(2, 3);

forPage.all();

//=> [4, 5, 6]
  • nth() 回到种种第x个成分,组成的集结

const collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);

const nth = collection.nth(4);

nth.all();

//=> ['a', 'e']
var values = [0,1,5,10,15];
values.sort();
alert(values); //0,1,10,15,5

以此获得什么样结果吧? 2,贰a,叁,a,a2,b

引入collect.js

用以总计出几个值的

  • avg() 算出平均值

collect([1, 3, 3, 7]).avg();

//=> 3.5

指标一旦是指标只怕3个多维数组,能够流传key值

const collection = collect([{
  name: 'JavaScript: The Good Parts', pages: 176
}, {
  name: 'JavaScript: The Definitive Guide', pages: 1096
}]);

collection.avg('pages');

//=> 636
  • sum([【4858美高梅】的办法库整理,js对象数组深度去重和纵深排序。key|callback]) 合计

arg1 关联数组的key

collect([1, 2, 3]).sum();

//=> 6

传扬第叁个参数,能够只合计此列

const collection = collect([
  {name: 'JavaScript: The Good Parts', pages: 176},
  {name: 'JavaScript: The Definitive Guide', pages: 1096},
]);

也得以流传回调,决定哪些item应被合计

const collection = collect([
  {name: 'Desk', colors: ['Black', 'Mahogany']},
  {name: 'Chair', colors: ['Black']},
  {name: 'Bookcase', colors: ['Red', 'Beige', 'Brown']},
]);

const total = collection.sum(function (product) {
  return product.colors.length;
});

//=> 6

collection.sum(‘pages’);

//=> 1272

* **count()** *计数*
```javascript
const collection = collect([1, 2, 3, 4]);

collection.count();

//=> 4```


* **max()** *最大值*
```javascript
const collection = collect([{
  value: 10
}, {
  value: -13
}, {
  value: 12
}, {
  unicorn: false
}]);

const max = collection.max('value');

//=> 12
  • min() 最小值

const collection = collect[{
  worth: 100
}, {
  worth: 900
}, {
  worth: 79
}]);

collection.min('worth');

//=> 79

collect([1, 2, 3, 4, 5]).min();

//=> 1
  • median() 中位数

collect([1, 3, 3, 6, 7, 8, 9]).median();

//=> 6

collect([{
  foo: 1
}, {
  foo: 1
}, {
  foo: 2
}, {
  foo: 4
}]).median('foo');

//=> 1.5
  • mode() 再次来到mode
    value,不佳意思,那几个其实没看懂,应该是壹种数学总计

collect([{
  foo: 1
}, {
  foo: 1
}, {
  foo: 2
}, {
  foo: 4
}]).mode('foo');

//=> [1]

collect([1, 3, 3, 6, 7, 8, 9]).mode();

//=> [3]
  • pipe()
    像管道一样,每一次回调都足以对聚集进行操作,下2遍回调得到的成团是事先操作后的集纳

const collection = collect([1, 2, 3]);

const piped = collection.pipe(function (collection) {
  return collection.sum();
});

//=> 6

由此,sort()方法能够吸收2个比较函数作为参数。

因为 数字的ascii码比字母的小,所以数字排在后边,字母排在末端。

分割

  • chunk() 分块取出

const collection = collect([1, 2, 3, 4, 5, 6, 7]);

const chunks = collection.chunk(4);

chunks.all();

//=> [[1, 2, 3, 4], [5, 6, 7]]
  • groupby() 按key来分组

const collection = collect([
  {
    product: 'Chair',
    manufacturer: 'IKEA'
  },
  {
    product: 'Desk',
    manufacturer: 'IKEA'
  },
  {
    product: 'Chair',
    manufacturer: 'Herman Miller'
  }
]);

const grouped = collection.groupBy('manufacturer');

grouped.all();

//=> {
//=>   IKEA: [
//=>     {
//=>       id: 100,
//=>       product: 'Chair',
//=>       manufacturer: 'IKEA',
//=>       price: '1490 NOK'
//=>     },
//=>     {
//=>       id: 150,
//=>       product: 'Desk',
//=>       manufacturer: 'IKEA',
//=>       price: '900 NOK'
//=>     }
//=>   ],
//=>   'Herman Miller': [
//=>     {
//=>       id: 200,
//=>       product: 'Chair',
//=>       manufacturer: 'Herman Miller',
//=>       price: '9990 NOK'
//=>     }
//=>   ]
//=> }

也得以流传回调函数,用于判断哪些分组

const collection = collect([
  {
    product: 'Chair',
    manufacturer: 'IKEA'
  },
  {
    product: 'Desk',
    manufacturer: 'IKEA'
  },
  {
    product: 'Chair',
    manufacturer: 'Herman Miller'
  }
]);

const grouped = collection.groupBy(function (item, key) {
  return item.manufacturer.substring(0, 3);
});

grouped.all();

//=> {
//=>   IKE: [
//=>     {
//=>       id: 100,
//=>       product: 'Chair',
//=>       manufacturer: 'IKEA',
//=>       price: '1490 NOK'
//=>     },
//=>     {
//=>       id: 150,
//=>       product: 'Desk',
//=>       manufacturer: 'IKEA',
//=>       price: '900 NOK'
//=>     }
//=>   ],
//=>   Her: [
//=>     {
//=>       id: 200,
//=>       product: 'Chair',
//=>       manufacturer: 'Herman Miller',
//=>       price: '9990 NOK'
//=>     }
//=>   ]
//=> }
  • keyBy() 按key分组

const collection = collect([
  {
    product: 'Chair',
    manufacturer: 'IKEA'
  }, {
    product: 'Desk',
    manufacturer: 'IKEA'
  }, {
    product: 'Chair',
    manufacturer: 'Herman Miller'
  }
]);

const keyed = collection.keyBy('manufacturer');

keyed.all();

//=> {
//=>   IKEA: {
//=>     product: 'Desk',
//=>     manufacturer: 'IKEA'
//=>   },
//=>   'Herman Miller': {
//=>     product: 'Chair',
//=>     manufacturer: 'Herman Miller'
//=>   }
//=> }

也得以流传2个回调来拍卖key,然后用处理过的key来分组

const keyedUpperCase = collection.keyBy(function (item) {
  return item['manufacturer'].toUpperCase();
});

keyedUpperCase.all();

//=> {
//=>   IKEA: {
//=>     product: 'Desk',
//=>     manufacturer: 'IKEA'
//=>   },
//=>   'HERMAN MILLER': {
//=>     product: 'Chair',
//=>     manufacturer: 'Herman Miller'
//=>   }
//=> }
  • partition() 按回调的回来值分区

const collection = collect([1, 2, 3, 4, 5, 6]);

const [underThree, overThree] = collection.partition(function (i) {
  return i < 3;
});
  • split(count,[index,[replaces]]) 将聚合分割成n份

const collection = collect([1, 2, 3, 4, 5]);

const groups = collection.split(3);

//=> [[1, 2], [3, 4], [5]]

其多少个参数能够顺便替换原有集合的items

const collection = collect([1, 2, 3, 4, 5]);

const chunk = collection.splice(2, 1, [10, 11]);

chunk.all()

//=> [3]

collection.all();

//=> [1, 2, 10, 11, 4, 5]
function compare(value1,value2){
if (value1 < value2){
return -1;
}else if (value1 > value2){
return 1;
}else{
return 0;
}
}

如果想继承让地点的数组arr遵照数字进行排序,怎么处理吧?

npm install collect.js --save

用于拍卖多维对象或数组

  • collapse()
    折叠,就是将聚合中装有嵌套的集纳,都平铺开来,输出成三个集合

const collection = collect([[1], [{}, 5, {}], ['xoxo']]);

const collapsed = collection.collapse();

collapsed.all();

//=> [1, {}, 5, {}, 'xoxo']

const collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

const collapsed = collection.collapse();

collapsed.all();

//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • flatten() 和collapse类似,一时半刻没察觉有哪些界别

const collection = collect({
  club: 'Liverpool',
  players: ['Sturridge', 'Firmino', 'Coutinho']
});

const flattened = collection.flatten();

flattened.all();

//=> ['Liverpool', 'Sturridge', 'Firmino', 'Coutinho'];

也得以流传深度

const collection = collect({
  Apple: [{
    name: 'iPhone 6S',
    brand: 'Apple'
  }],
  Samsung: [{
    name: 'Galaxy S7',
    brand: 'Samsung'
  }]
});

const flattened = collection.flatten(1);

flattened.all();

//=> [
//=>   {name: 'iPhone 6S', brand: 'Apple'},
//=>   {name: 'Galaxy S7', brand: 'Samsung'}
//=> ]
  • combine()
    整合,将原集协作为key,参数集合营为value,组合成3个对象

const collection = collect(['name', 'number']);

const combine = collection.combine(['Steven Gerrard', 8]);

combine.all();

//=> {
//=>   name: 'Steven Gerrard',
//=>   number: 8
//=> }
  • zip() 将原集合当作key,参数集合当成value,组成关联数组

const collection = collect(['Chair', 'Desk']);

const zipped = collection.zip([100, 200]);

zipped.all();

//=> [['Chair', 100], ['Desk', 200]]

此相比函数可适用于多数数据类型,只要将其看成参数字传送递给sort()方法即可:

JavaScript给大家提供了3个输入,能够给sort()
方法传递四个参数,即相比较函数,来报告排序算法值与值时期是凌驾、小于依旧十分关系。

用于组合集合

  • concat() 联合,其实和merge有点像,将三个或七个item插手到集结中

const collection = collect([1, 2, 3]);

collection
  .concat(['a', 'b', 'c'])
  .concat({
    name: 'Steven Gerrard',
    number: 8
  });

collection.all();

//=> [1, 2, 3, 'a', 'b', 'c', 'Steven Gerrard', 8]
  • crossJoin() 排列组合

const collection = collect([1, 2]);

collection.crossJoin(['a', 'b']);

collection.all();

//=> [
//=>   [1, 'a'],
//=>   [1, 'b'],
//=>   [2, 'a'],
//=>   [2, 'b'],
//=> ]
  • union(collection)
    构成集合,按key来判定,假诺有双重的key,就用原集合的item

const collection = collect({
  a: 'A',
  b: 'B'
});

const union = collection.union({
  a: 'AAA',
  c: 'CCC',
  b: 'BBB'
});

union.all();

//=> {
//=>   a: 'A',
//=>   b: 'B',
//=>   c: 'CCC'
//=> }
  • diff() 取第三个聚众中有些,但第一个汇聚中从不的item,组成集合

const collection = collect([1, 2, 3, 4, 5]);

const diff = collection.diff([1, 2, 3, 9]);

diff.all();

//=> [4, 5]
  • diffAssoc()
    和diff()类似,但针对对象或提到数组相比较,会同时比较key和value

const collection = collect({
  color: 'orange',
  type: 'fruit',
  remain: 6,
});

const diff = collection.diffAssoc({
  color: 'yellow',
  type: 'fruit',
  remain: 3,
  used: 6,
});

diff.all();

//=> { color: 'orange', remain: 6 };
  • diffKeys() 和diff()一样,但只相比较key

const collection = collect({
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd'
});

const diff = collection.diffKeys({
  b: 'b',
  d: 'd'
});

diff.all();

//=> {a: 'a', c: 'c'}
  • intersect() 取交集

const collection = collect([1, 2, 3, 4, 5]);

intersect = collection.intersect([1, 2, 3, 9]);

intersect.all();

//=> [1, 2, 3]
  • intersectByKeys() 按key取交集

const collection = collect({
    serial: 'UX301',
    type: 'screen',
    year: 2009,
});

const intersect = collection.intersectByKeys({
  reference: 'UX404',
  type: 'tab',
  year: 2011,
});

intersect.all();

// ['type' => 'screen', 'year' => 2009]

const firstCollection = collect([1, 2, 3, 4, 5]);
const secondCollection = collect([1, 2, 3, 9]);

intersect = firstCollection.intersect(secondCollection);

intersect.all();

//=> [1, 2, 3]
  • merge() 结缘三个相同结构的聚集

const collection = collect({
  id: 1,
  price: 29
});

const merged = collection.merge({
  price: 400,
  discount: false
});

merged.all();

//=> {id: 1, price: 400, discount: false}

const collection = collect(['Unicorn', 'Rainbow']);

const merged = collection.merge(['Sunshine', 'Rainbow']);

merged.all();

//=> ['Unicorn', 'Rainbow', 'Sunshine', 'Rainbow']
var values = [0,1,3,7,9,15];
values.sort(compare);
alert(values); //0,1,3,7,9,15

相比较函数是拥有特定算法的函数。

<script src="https://cdn.jsdelivr.net/npm/collect.js@4.0.25/build/collect.min.js"></script>

用以操作集合内的

  • contains() * 判断集合内是或不是钦点的key*

操作对象时,类似于hasOwnProperty
操作数组时,类似于indexOf(value) === -一

操作对象

const collection = collect({
  name: 'Steven Gerrard',
  number: 8
});

collection.contains('name');
//=> true

collection.contains('age');
//=> false

对数组操作

const collection = collect([1, 2, 3]);

collection.contains(3);
//=> true

对key和value1起判断

const collection = collect({
  name: 'Steven Gerrard',
  number: 8
});

collection.contains('name', 'Steve Jobs');
//=> false
  • has() 判定是还是不是存在对应的key

操作对象时,效果应该与 contains() 相同

const collection = collect({
  animal: 'unicorn',
  ability: 'magical'
});

collection.has('ability');

//=> true
  • get() 按key取出value,假诺找不取,就回到第三个参数(即暗中同意值)

const collection = collect({
  firstname: 'Chuck',
  lastname: 'Norris'
});

collection.get('lastname');

//=> Norris

collection.get('middlename');
//=> null

其次个参数作为找到不时,再次来到的暗中认可值

const collection = collect({
  firstname: 'Chuck',
  lastname: 'Norris'
});

collection.get('middlename', 'default-value');
//=> default-value

暗中同意值也得以是回调

const collection = collect({
  firstname: 'Chuck',
  lastname: 'Norris'
});

collection.get('middlename', function () {
  return 'default-value';
});

//=> default-value
  • search() 按value获取key

const collection = collect([2, 4, 6, 8]);

collection.search(4);

//=> 1

第1个参数传入true时,全数value比较时,整数字符串会被当下阶段的整数相比

collection.search('4', true);

//=> false

也足以用回调查找

collection.search(function (item, key) {
  return item > 5;
});

//=> 2
  • first() 取出第2个item,也足以流传八个回调函数

collect([1, 2, 3, 4]).first();

//=> 1

collect([1, 2, 3, 4]).first(function (item) {
  return item > 1;
});

//=> 2
  • firstWhere() 按key-value来判断,找出第三个item

const collection = collect([
    {name: 'Regena', age: 12},
    {name: 'Linda', age: 14},
    {name: 'Diego', age: 23},
    {name: 'Linda', age: 84},
]);

collection.firstWhere('name', 'Linda');

//=> { name: 'Linda', age: 14 }
  • last() 回到最终三个item

const collection = collect([1, 2, 3]);

const last = collection.last(function (item) {
  return item > 1;
});

//=> 3

collect([1, 2, 3, 4]).last();

//=> 4
  • forget() 用key删除叁个item

const collection = collect({
  name: 'Steven Gerrard',
  number: 8
});

collection.forget('number');

collection.all();

//=> {
//=>   name: 'Steven Gerrard'
//=> }
  • pad()
    *用固定的值填充集合,第1个参数是填充后的集纳长度,第3个参数是填充的值

const collection = collect(['A', 'B', 'C']);

let filtered = collection.pad(5, 0);

filtered.all();

//=> ['A', 'B', 'C', 0, 0]

filtered = collection.pad(-5, 0);

filtered.all();

//=> [0, 0, 'A', 'B', 'C']
  • pop() 压出最终多个item

const collection = collect([1, 2, 3, 4, 5]);

collection.pop();

//=> 5

collection.all();

// => [1, 2, 3, 4]
  • prepend() 压入2个item,并将它身处集合的第多少个

const collection = collect([1, 2, 3, 4, 5]);

collection.prepend(0);

collection.all();

//=> [0, 1, 2, 3, 4, 5]

也得以流传第二个参数,作为压入item的key

const collection = collect({
  product: 'iPhone 6s'
});

collection.prepend('Apple', 'brand');

collection.all():

//=> {
//=>   brand: 'Apple',
//=>   product: 'iPhone 6s'
//=> }
  • pull() 删去钦命key的item,(笔者以为叫delete更适用)

const collection = collect({
  firstname: 'Michael',
  lastname: 'Cera'
});

collection.pull('lastname');

//=> Cera

collection.all();

//=> {firstname: 'Michael'}
  • push() 压入1个item,放在集合最后

const collection = collect([1, 2, 3, 4]);

collection.push(5);

collection.all();

//=> [1, 2, 3, 4, 5]
  • put() 像是参加叁个item到集结中,但没看懂示例

const collection = collect(['JavaScript', 'Python']);

collection.put('Ruby');

collection.all();

//=> ['JavaScript', 'Python', 'Ruby']
  • shift() 从底部压出item

const collection = collect([1, 2, 3, 4, 5]);

collection.shift();

//=> 1

collection.all();

//=> [2, 3, 4, 5]
  • random() 专断取出item

const collection = collect([1, 2, 3, 4, 5]);

collection.random();

//=> 4 (retrieved randomly)

能够内定取出多少个

const random = collection.random(3);

//=> [5, 3, 4] (retrieved randomly)
  • reduce()
    和pipe()类似,只是每便回调传入[上一个item,当前item]五个参数

const collection = collect([1, 2, 3]);

const total = collection.reduce(function (carry, item) {
  return carry + item;
});

//=> 6
  • splice() 删除多少个item,第3个参数是从头的index

const collection = collect([1, 2, 3, 4, 5]);

const chunk = collection.splice(2);

chunk.all();

//=> [3, 4, 5]

collection.all();

//=> [1, 2]

const collection = collect([1, 2, 3, 4, 5]);

const chunk = collection.splice(2, 1);

chunk.all();

//=> [3]

collection.all();

//=> [1, 2, 4, 5]
  • take(n) 取出n个item

arg1 指取出多少个item

const collection = collect([0, 1, 2, 3, 4, 5]);

const chunk = collection.take(3);

chunk.all();

//=> [0, 1, 2]

也可经过相比函数发生降序排序,只需调换函数再次来到值即可:

function compare_fn(value1, value2) {
 if (value1 < value2) {
 return -1;
 } else if (value1 > value2) {
 return 1;
 } else {
 return 0;
 }
}

 

遍历

  • each() 遍历各样item,但不改动集合

let sum = 0;

const collection = collect([1, 3, 3, 7]);

collection.each(function (item) {
  sum += item;
});

//=> console.log(sum);
//=> 14

假诺你在回调中回到false,则会及时停下遍历

let sum = 0;

const collection = collect([1, 3, 3, 7]);

collection.each(function (item) {
  if (item > 3) {
    return false;
  }

  sum += item;
});

//=> console.log(sum);
//=> 7
  • eachSpread() each()的递归版本,它会递归调用each()

const collection = collect([['John Doe', 35], ['Jane Doe', 33]]);

collection.eachSpread((name, age) => {
    //
});

一律的,你也得以在回调中回到false,就能即刻停下遍历

collection.eachSpread((name, age) => {
    return false;
});
  • transform() 遍历集合,每种回调的回到值会替换当成item

const collection = collect([1, 2, 3, 4, 5]);

collection.transform(function (item, key) {
  return item * 2;
});

collection.all();

//=> [2, 4, 6, 8, 10]
  • flatMap()
    用回调遍历集合,在回调中得以获得value,利用回调中的再次来到值,按原集合格式,组成新的会晤,并赶回

const collection = collect([
 { name: 'Robbie Fowler' },
 { nickname: 'The God' },
 { position: 'Striker' },
]);

const flatMapped = collection.flatMap(values => values.map(value => value.toUpperCase()));

flatMapped.all();

//=> {
//=>   name: 'ROBBIE FOWLER',
//=>   nickname: 'THE GOD',
//=>   position: 'STRIKER'
//=> }
  • map() 遍历每个value,用回调实行修改后,重临新集合

const collection = collect([1, 2, 3, 4, 5]);

const multiplied = collection.map(function (item) {
  return item * 2;
});

multiplied.all();

//=> [2, 4, 6, 8, 10]
  • mapSpread() map()的递归版本

const collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

const chunks = collection.chunk(2);

const sequence = chunks.mapSpread((odd, even) => {
    return odd + even;
});

sequence.all();

//=> [1, 5, 9, 13, 17]
  • slice() 从某1个index开始分片

const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

const slice = collection.slice(4);

slice.all();

//=> [5, 6, 7, 8, 9, 10]

第一个参数是回来的item长度

const slice = collection.slice(4, 2);

slice.all();

//=> [5, 6]
  • mapInto()
    传播的回调是1个类的构造器,此办法将各类item传入回调,作为构造器的参数,回调器的回来便是三个对象,最后回到一组对象

const Player = function (name) {
  this.name = name;
};

const collection = collect([
  'Roberto Firmino',
  'Sadio Mané',
]);

const players = collection.mapInto(Player);

players.all();

//=> [
//=>   Player { name: 'Roberto Firmino' },
//=>   Player { name: 'Sadio Mané' },
//=> ]
  • mapToDirctionary() 遍历后,再次来到一组关全面组

const collection = collect([
  { id: 1, name: 'a' },
  { id: 2, name: 'b' },
  { id: 3, name: 'c' },
  { id: 4, name: 'b' },
]);

const groups = collection.mapToDictionary(item => [item.name, item.id]);

groups.all();

//=> {
//=>   a: [1],
//=>   b: [2, 4],
//=>   c: [3],
//=> }
  • mapToGroups
    和mapToDirctionary()1样,只是本次回调的第一个参数尚可key

const collection = collect([
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 3, name: 'C' },
  { id: 4, name: 'B' },
]);

const groups = collection.mapToGroups(function (item, key) {
  return [item.name, item.id];
});

//=> {
//=>   A: [1],
//=>   B: [2, 4],
//=>   C: [3],
//=> }
  • mapWithKeys()
    和map1样,只是回调应该回到一个[key,value]的数组,最后方法再次回到壹组关周全组

const collection = collect([{
    'name': 'John',
    'department': 'Sales',
    'email': 'john@example.com'
  }, {
    'name': 'Jane',
    'department': 'Marketing',
    'email': 'jane@example.com'
  }]);

const keyed = collection.mapWithKeys(function (item) {
  return [item.email, item.name];
});

keyed.all();

//=> {
//=>   'john@example.com': 'John',
//=>   'jane@example.com': 'Jane',
//=> }
function compare (value1, value2){
if (value1<value2){
return 1;
}else if {
return -1;
}else{
return 0;
}
}

将相比函数 compare_fn 传递给sort,再实行排序,然后输出

深度去重

判断集合的一蹴而就

  • every()
    认清集合中的item是还是不是每二个都灵验,怎样才算有效,就由回调函数来判定

collect([1, 2, 3, 4]).every(function (value, key) {
  return value > 2;
});

//=> false
  • isEmpty() 是还是不是为空集合

collect([]).isEmpty();

//=>  true
  • isNotEmpty 是还是不是为非空集合

collect([1, 2, 3]).isNotEmpty();

//=>  true

sort()函数的排序条件是:

arr.sort(compare_fn);
alert(arr);  得到 1, 2, 3, 12, 21

过滤

  • except() 删去传入的item,并赶回新集合

操作对象时,按key判断
操作数组时,按value判断
和diff()比较,好像只是把原集合和传唱集合对调了弹指间

const collection = collect({
  product_id: 1,
  price: 100,
  discount: false,
});

const filtered = collection.except(['price', 'discount']);

filtered.all();

//=> {product_id: 1}

collect([1, 2, 3, 4]).except([2, 12]).all();

//=> [1, 3, 4]
  • only() 和except是相反的操作

const collection = collect({
  id: 12,
  name: 'John Doe',
  email: 'john@doe.com',
  active: true,
});

const filtered = collection.only(['name', 'email']);

filtered.all();

//=> {name: 'John Doe', email: 'john@doe.com'}
  • filter() 按回调的重临值过滤集合,并回到过滤后的集合

const collection = collect([1, 2, 3, 4]);

const filtered = collection.filter(function (value, key) {
    return value > 2;
});

filtered.all();

//=> [3, 4]

也得以流传空回调,那样等于false的值,都会被过滤掉

const collection = collect([0, 1, 2, null, 3, 4, undefined, 5, 6, 7, [], 8, 9, {}, 10]);

const filtered = collection.filter();

filtered.all();

//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • reject()
    4858美高梅 ,filter()的反操作,回调中回到true的item,都将被删去后回来

const collection = collect([1, 2, 3, 4]);

const filtered = collection.reject(function (value) {
  return value > 2;
});

//=> [1, 2]
  • where(key,[op],value) 搜寻key-value对,并将其任何回到

key 贰维表的key
op 此参数能够是三个操作符,包蕴<,<=,>,>=
value 2维表的值

const collection = collect([
  {product: 'Desk', price: 200},
  {product: 'Chair', price: 100},
  {product: 'Bookcase', price: 150},
  {product: 'Door', price: 100},
]);

* **whereIn(key,collection)** *where的in-array操作*
```javascript
const collection = collect([
  {product: 'Desk', price: 200},
  {product: 'Chair', price: 100},
  {product: 'Bookcase', price: 150},
  {product: 'Door', price: 100},
]);

const filtered = collection.whereIn('price', [100, 150]);

filtered.all();

//=> [
//=>   {product: 'Chair', price: 100},
//=>   {product: 'Bookcase', price: 150},
//=>   {product: 'Door', price: 100},
//=> ]
  • whereNotIn(key,collection) where的not in-array操作

const collection = collect([
  { product: 'Desk', price: 200 },
  { product: 'Chair', price: 100 },
  { product: 'Bookcase', price: 150 },
  { product: 'Door', price: 100 }
]);

const filtered = collection.whereNotIn('price', [150, 200]);

filtered.all();

//=> [
//=>   { product: 'Chair', price: 100 },
//=>   { product: 'Door', price: 100 }
//=> ]

const filtered = collection.where(‘price’, 100);

filtered.all();

//=> [
//=> {product: ‘Chair’, price: 100},
//=> {product: ‘Door’, price: 100}
//=> ]

第2个参数还可以是一个操作符
```javascript
const filtered = collection.where('price', '!==', 100);

filtered.all();

//=> [
//=>   {product: 'Desk', price: 200},
//=>   {product: 'Bookcase', price: 150}
//=> ]
  • unique(key|callback) 取重

const collection = collect([1, 1, 1, 2, 3, 3]);

const unique = collection.unique();

unique.all();

//=> [1, 2, 3]

在关周到组时,能够只去重某一列

const collection = collect([
  {name: 'iPhone 6', brand: 'Apple', type: 'phone'},
  {name: 'iPhone 5', brand: 'Apple', type: 'phone'},
  {name: 'Apple Watch', brand: 'Apple', type: 'watch'},
  {name: 'Galaxy S6', brand: 'Samsung', type: 'phone'},
  {name: 'Galaxy Gear', brand: 'Samsung', type: 'watch'}
]);

const unique = collection.unique('brand');

unique.all();

//=> [
//=>   {name: 'iPhone 6', brand: 'Apple', type: 'phone'},
//=>   {name: 'Galaxy S6', brand: 'Samsung', type: 'phone'},
//=> ]

也能够用callback来决定,哪些item要去重

const collection = collect([
  {name: 'iPhone 6', brand: 'Apple', type: 'phone'},
  {name: 'iPhone 5', brand: 'Apple', type: 'phone'},
  {name: 'Apple Watch', brand: 'Apple', type: 'watch'},
  {name: 'Galaxy S6', brand: 'Samsung', type: 'phone'},
  {name: 'Galaxy Gear', brand: 'Samsung', type: 'watch'}
]);

const unique = collection.unique(function (item) {
  return item.brand + item.type;
});

unique.all();

//=> [
//=>   {name: 'iPhone 6', brand: 'Apple', type: 'phone'},
//=>   {name: 'Apple Watch', brand: 'Apple', type: 'watch'},
//=>   {name: 'Galaxy S6', brand: 'Samsung', type: 'phone'},
//=>   {name: 'Galaxy Gear', brand: 'Samsung', type: 'watch'},
//=> ]

参数大于0,arr的相近四个要素交流地方;

JavaScript中Array对象的sort方法重返值的定义为

归纳数组去重

只操作对象和关周密组

  • flip() 反转key和value

const collection = collect({
  name: 'Steven Gerrard',
  number: 8
});

const flipped = collection.flip();

flipped.all();

//=> {
//=>   'Steven Gerrard': 'name',
//=>   '8': 'number'
//=> }
  • implode() 把item展开

操作对象(关联数组)时,可以钦赐一个key,将此key对应的value展开

const collection = collect([{
    product: 'Chair',
    manufacturer: 'IKEA',
  }, {
    product: 'Desk',
    manufacturer: 'IKEA',
  }, {
    product: 'Chair',
    manufacturer: 'Herman Miller',
  }]);

collection.implode('product', ',');

//=> Chair, Desk, Chair

操作一维数组时,能够流传第四个参数当成连接符使用

collect([1, 2, 3, 4, 5]).implode('-');

//=> 1-2-3-4-5
  • keys() 只返回key列表

const collection = collect([{
  name: 'Steven Gerrard',
  number: 8
}, {
  club: 'Liverpool',
  nickname: 'The Reds'
}]);

keys = collection.keys();

//=> ['name', 'number', 'club', 'nickname']
  • values() 只返回value的列表

const collection = collect({a: 'xoxo', b: 'abab', 'c': '1337', 1337: 12});

const values = collection.values();

values.all();

//=> [12, 'xoxo', 'abab', '1337']
  • pluck() 将聚集看成一个二维表格,重返某一列的value组成的集纳

const collection = collect([{
  id: 78,
  name: 'Aeron'
}, {
  id: 79,
  name: 'Embody'
}]);

const plucked = collection.pluck('name');

plucked.all();

//=> ['Aeron', 'Embody']

归来的聚合的key,能够用表格中的另1列的value

const collection = collect([{
  id: 78,
  name: 'Aeron'
}, {
  id: 79,
  name: 'Embody'
}]);

const plucked = collection.pluck('name', 'id');

plucked.all();

//=> {
//=>   78: 'Aeron',
//=>   79: 'Embody'
//=> }

参数小于0,arr的隔壁多个元素不调换地方;

负值 : 假若所传递的首先个参数比第四个参数小

const collection = collect([1, 1, 1, 2, 3, 3]);

const unique = collection.unique();

unique.all();

//=> [1, 2, 3]

输出

  • dd() 出口到console.log,并甘休程序

const collection = collect([1, 2, 3]).dd();

//=> [1, 2, 3]
//=> (Exits node.js process)
  • dump() 和dd()一样,只是不刹车输出

collect([1, 2, 3, 4])
  .dump()
  .map(item => item * 2)
  .dump();

//=> [1, 2, 3, 4]
//=> [2, 4, 6, 8]
  • toArray() 转成array

const collection = collect([1, 2, 3, 'b', 'c']);

collection.toArray();

//=> [1, 2, 3, 'b', 'c']

const collection = collect({
  name: 'Elon Musk',
  companies: [
    'Tesla',
    'Space X',
    'SolarCity'
  ]
});

collection.toArray();

//=> ['Elon Musk', ['Tesla', 'Space X', 'SolarCity']]
  • toJson() 转成json

const collection = collect({
  id: 384,
  name: 'Rayquaza',
  gender: 'NA'
});

const json = collection.toJson();

//=> {"id": 384, "name": "Rayquaza", "gender": "NA"}
  • unwrap() 重返原有的靶子

const collection = collect([1, 2, 3]);

collect().unwrap(collection);

//=> [1, 2, 3]

参数等于0,arr的隔壁多少个成分大小相等;所以compare自定义函数必须回到三个数值。

零 : 四个值相当

对象数组去重

排序

  • soft() 排序

const collection = collect([5, 3, 1, 2, 4]);

const sorted = collection.sort();

sorted.all();

//=> [1, 2, 3, 4, 5]

能够用回调排序

const collection = collect([5, 3, 1, 2, 4]);

const sorted = collection.sort(function (a, b) {
  return b - a;
});

sorted.all();

//=> [5, 4, 3, 2, 1]
  • shuffle() 乱序排列

const collection = collect([1, 2, 3, 4, 5]);

const shuffled = collection.shuffle();

shuffled.all();

//=> [3, 5, 1, 2, 4] (generated randomly)
  • reverse() 反转集合,即倒序排列

const collection = collect([1, 2, 3, 4, 5]);

const reversed = collection.reverse();

reversed.all();

//=> [5, 4, 3, 2, 1]
  • softBy 按key来排序

const collection = collect([
  {name: 'Desk', price: 200},
  {name: 'Chair', price: 100},
  {name: 'Bookcase', price: 150},
]);

const sorted = collection.sortBy('price');

sorted.all();

//=> [
//=>   {name: 'Chair', price: 100},
//=>   {name: 'Bookcase', price: 150},
//=>   {name: 'Desk', price: 200},
//=> ]

const collection = collect([
  {name: 'Desk', colors: ['Black', 'Mahogany']},
  {name: 'Chair', colors: ['Black']},
  {name: 'Bookcase', colors: ['Red', 'Beige', 'Brown']},
]);

const sorted = collection.sortBy(function (product, key) {
  return product['colors'].length;
});

sorted.all();

//=> [
//=>   {name: 'Chair', colors: ['Black']},
//=>   {name: 'Desk', colors: ['Black', 'Mahogany']},
//=>   {name: 'Bookcase', colors: ['Red', 'Beige', 'Brown']},
//=> ]
  • sortByDesc() 和sortBy(),只是排序方一贯降序

贰.对于数值类型或许valueOf()方法会再次回到数值类型的目的类型。

正值 : 如若第一个参数比第3个参数大

const collection = collect([
  { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
  { name: 'iPhone 5', brand: 'Apple', type: 'phone' },
  { name: 'Apple Watch', brand: 'Apple', type: 'watch' },
  { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
  { name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' },
]);

const unique = collection.unique('brand');

unique.all();

//=> [
//=>   { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
//=>   { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
//=> ]

扩展

  • macro() 能够为collection类定义一个自定义方法

但不可能用来链式调用

collect().macro('uppercase', function () {
  return this.map(function (item) {
    return item.toUpperCase();
  });
});

const collection = collect(['a', 'b', 'c']);

collection.uppercase();

collection.all();

//=> ['A', 'B', 'C']
  • tap(callback(collection)) 给回调函数字传送入合集,但不容许修改集合

此方法常用于链式调用

const collect([2, 4, 3, 1, 5])
  .sort()
  .tap(function (collection) {
    console.log(collection.all());

    //=> [1, 2, 3, 4, 5]
  })
  .shift();

//=> 1
  • unless(bool,callback) 随处用回调循环,除非第二个参数的值为假

bool 当为假时,循环甘休
callback = function(collection),即callback的第叁个参数是会面自个儿

const collection = collect([1, 2, 3]);

collection.unless(false, function (collection) {
  return collection.push(4);
});

collection.all();

//=> [1, 2, 3, 4]
  • when(bool,callback) 持续用回调循环,除非第三个参数的值为假

bool 当为真时,循环甘休
callback = function(collection),即callback的第二个参数是集聚自身

const collection = collect([1, 2, 3]);

collection.when(true, function (collection) {
  return collection.push(4);
});

collection.all();

//=> [1, 2, 3, 4]
  • wrap() 包装

const collection = collect().wrap([1, 2, 3]);

collection.all();

//=> [1, 2, 3]

可使用多少个更简明的可比函数。此函数只要首个值减第3个值即可。

下面的比较函数还足以简写为

对象数组回调函数处理去重

function compare (value1,value2){
return value2 - value1;
}
function compare_fn(value1, value2) {
 return value1 - value2;
}
const collection = collect([
  { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
  { name: 'iPhone 5', brand: 'Apple', type: 'phone' },
  { name: 'Apple Watch', brand: 'Apple', type: 'watch' },
  { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
  { name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' },
]);

const unique = collection.unique(function (item) {
  return item.brand + item.type;
});

unique.all();

//=> [
//=>   { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
//=>   { name: 'Apple Watch', brand: 'Apple', type: 'watch' },
//=>   { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
//=>   { name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' },
//=> ]

如上所述是作者给我们介绍的JS中数组重排序方法,希望对大家全部帮忙,倘诺我们有任何疑问请给本身留言,我会及时复苏我们的。在此也分外谢谢大家对台本之家网址的支撑!

其1比较的为升序排列

 

您大概感兴趣的篇章:

  • JavaScript贯彻链表插入排序和链表归并排序
  • JavaScript排序算法动画演示效果的贯彻格局
  • js利用appendChild对<li>标签实行排序的兑现格局
  • 浅谈js控制li标签排序问题js调用php函数的不2秘籍
  • js基本算法:冒泡排序,二分查找的简短实例
  • javascript数组对象常用api函数小结(连接,插入,删除,反转,排序等)
  • AngularJS
    过滤与排序详解及实例代码
  • JavaScript算法连串之迅捷排序(Quicksort)算法实例详解
  • JavaScript
    冒泡排序和挑选排序的达成代码
  • 基于javascript完成的登时排序

只要想降序排列,间接改动下边包车型客车再次回到值的符号就足以了,给拥有重回均取反。

总结排序和深度排序

对简写的比较函数就是

简单来讲数组排序

function compare_fn(value1, value2) {
 return -(value1 - value2);
}   

const collection = collect([5, 3, 1, 2, 4]);

const sorted = collection.sort();

sorted.all();

//=> [1, 2, 3, 4, 5]
function compare_fn(value1, value2) {
 return value2 - value1;
}

简单数组回调函数处理排序

粗略的记法便是:顺序升;逆序降。

const collection = collect([5, 3, 1, 2, 4]);

const sorted = collection.sort(function (a, b) {
  return b - a;
});

sorted.all();

//=> [5, 4, 3, 2, 1]

以上这篇数组Array的排序sort方法正是作者分享给我们的全体内容了,希望能给大家八个参考,也指望我们多多帮助脚本之家。

对象数组排序

你或然感兴趣的作品:

  • js使用Array.prototype.sort()对数组对象排序的点子
  • js中数组(Array)的排序(sort)注意事项表明
  • js中的数组Array定义与sort方法运用示例
  • js数组Array
    sort方法运用深远解析
const collection = collect([
  { name: 'Desk', price: 200 },
  { name: 'Chair', price: 100 },
  { name: 'Bookcase', price: 150 },
]);

const sorted = collection.sortBy('price');

sorted.all();

//=> [
//=>   { name: 'Chair', price: 100 },
//=>   { name: 'Bookcase', price: 150 },
//=>   { name: 'Desk', price: 200 },
//=> ]

目的数组回调函数处理排序

const collection = collect([
  { name: 'Desk', colors: ['Black', 'Mahogany'] },
  { name: 'Chair', colors: ['Black'] },
  { name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
]);

const sorted = collection.sortBy(function (product, key) {
  return product['colors'].length;
});

sorted.all();

//=> [
//=>   { name: 'Chair', colors: ['Black'] },
//=>   { name: 'Desk', colors: ['Black', 'Mahogany'] },
//=>   { name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
//=> ]

降序排序

选拔方式和sortBy一样,但收获降序结果

 

==============================================

本文链接:

==============================================

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有