JS中数组重排序方法,的法子库整理

澳门葡京 1

collect.js 是
javascript的2个包装库,用于拍卖array和object,能够用它轻松得建立叁个map可能涂改现有的,可惜它的不贰诀要名实在有点难懂,特别是对大家那一个英文不是母语的人来说,所以就想把它整理一下,以往能够查找。

一.数组中已存在八个可直接用来重排序的措施:reverse()和sort()。

JavaScript中的Array对象有友好的排序方法sort(),对数组中的数据项实行排序,可是有时排序结果不顺手,比如

 

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

reverse()和sort()方法的重返值是因而排序后的数组。reverse()方法会反转数组项的逐1:

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());

 

用来取出集合中的1有些

  • 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

本条获得什么样结果吧? 二,二a,三,a,a二,b

引入collect.js

用来总括出贰个值的

  • avg() 算出平均值

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

//=> 3.5

目的1旦是目的大概一个多维数组,能够流传key值

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

collection.avg('pages');

//=> 636
  • sum([key|callback]) 合计

arg1 关联数组的key

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

//=> 6

传播第2个参数,能够只合计此列

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,倒霉意思,那些实际上没看懂,应该是1种数学计算

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

//=> [1]

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

//=> [3]
  • pipe()
    像管道一样,每一趟回调都能够对聚集实行操作,下3回回调得到的汇集是在此以前操作后的集聚

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

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

//=> 6

于是,sort()方法能够接过八个比较函数作为参数。

因为 数字的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() JS中数组重排序方法,的法子库整理。按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'
//=>   }
//=> }

也足以流传三个回调来拍卖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,组合成三个指标

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给大家提供了贰个输入,能够给sort()
方法传递二个参数,即相比较函数,来告诉排序算法值与值时期是凌驾、小于依旧至极关系。

用于组合集合

  • concat() 统1,其实和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()1样,但只相比较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和value壹起判断

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() 取出第陆个item,也得以流传1个回调函数

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

//=> 1

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

//=> 2
  • firstWhere() 按key-value来判断,找出第3个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删除1个item

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

collection.forget('number');

collection.all();

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

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() 压入贰个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() 从某三个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()
    传扬的回调是一个类的构造器,此格局将各种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()壹样,只是此番回调的第一个参数能够承受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样,只是回调应该回到1个[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()
    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 此参数能够是1个操作符,包罗<,<=,>,>=
value 贰维表的值

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

操作壹维数组时,可以流传第1个参数当成连接符使用

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自定义函数必须重返二个数值。

零 : 三个值10分

指标数组去重

排序

  • 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()方法会再次回到数值类型的对象类型。

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

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]

可使用三个更简便易行的比较函数。此函数只要首个值减第一个值即可。

地点的比较函数还是能够简写为

目的数组回调函数处理去重

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中数组重排序方法,希望对我们具有支持,假诺我们有别的疑问请给自身留言,我会及时还原我们的。在此也非常多谢大家对剧本之家网址的帮忙!

以此对比的为升序排列

 

你可能感兴趣的稿子:

  • JavaScript贯彻链表插入排序和链表归并排序
  • JavaScript排序算法动画演示效果的兑现模式
  • js利用appendChild对<li>标签实行排序的兑现格局
  • 浅谈js控制li标签排序难点js调用php函数的情势
  • 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'] },
//=> ]

降序排序

采纳办法和sortBy1样,但收获降序结果

 

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

本文链接:

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

相关文章

发表评论

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

*
*
Website