原文: http://zetcode.com/javascript/collectjs/

Collect.js 教程展示了如何使用 Collect.js 库处理 JavaScript 中的数组和对象。

Collect.js

Collect.js 是用于处理数组和对象的流畅,便捷的包装器。 它是 Laravel 集合的接口。 它包含许多使数据处理更加容易的函数。

Collect.js 帮助程序员编写更简洁,更易于维护的 JavaScript 代码。

Collect.js 安装

首先,我们安装 Collect.js 库。

  1. $ npm init
  2. $ npm i collect.js

collect.js库与npm一起本地安装。

collect()函数

我们将带有collect()的 JavaScript 数组转换为一个集合,并对该集合应用函数。 最后,我们使用all()toArray()返回底层数组。

Collect.js all()toArray

all()toArray()函数从集合中返回基础数组。 这两个函数之间的区别在于toArray()函数还将嵌套的集合转换为数组(如果存在)。

all_toarray.js

  1. const collect = require('collect.js');
  2. const nums1 = [1, 2, 3];
  3. const nums2 = [4, 5, 6];
  4. const data = collect([collect(nums1),
  5. collect(nums2)]);
  6. console.log(data.all());
  7. console.log(data.toArray());

该示例显示了两个函数之间的区别。

  1. $ node all_toarray.js
  2. [ Collection { items: [ 1, 2, 3 ] },
  3. Collection { items: [ 4, 5, 6 ] } ]
  4. [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

这是输出。 我们可以看到在第二个示例中,嵌套集合被转换为数组。

Collect.js count()

count()函数计算集合中元素的数量。

count_elements.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. const data = collect(nums);
  4. const nOfElements = data.count();
  5. console.log(`There are ${nOfElements} elements`);

该示例计算数组中值的数量。

  1. $ node count_elements.js
  2. Therea are 10 elements

Collect.js unique()

unique()函数返回集合中的所有唯一项。

unique.js

  1. const collect = require('collect.js');
  2. const nums = [1, 1, 1, 2, 4, 4, 5];
  3. const data = collect(nums);
  4. const unique_data = data.unique();
  5. console.log(unique_data.all());

该示例显示数组的唯一值。

  1. const unique_data = data.unique();

我们使用unique()从集合中获取所有唯一值。

  1. console.log(unique_data.all());

all()函数返回该集合表示的基础数组。

  1. $ node unique.js
  2. [ 1, 2, 4, 5 ]

这是输出。

first

第一个函数返回通过给定真值测试的集合中的第一个元素,或者仅返回第一个值。

first_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, -3, 4, -5, 6, 7, 8];
  3. const data = collect(nums);
  4. let fval = data.first();
  5. console.log(fval);
  6. let fneg = data.first(e => e < 0);
  7. console.log(fneg);

该示例打印第一个值和第一个负值。

  1. $ node first_fun.js
  2. 1
  3. -3

这是输出。

firstWhere

firstWhere函数返回具有给定键/值对的集合中的第一个元素。

firstwhere_fun.js

  1. const collect = require('collect.js');
  2. const users = [
  3. { name: 'John', city: 'London', born: '2001-04-01' },
  4. { name: 'Lenny', city: 'New York', born: '1997-12-11' },
  5. { name: 'Andrew', city: 'Boston', born: '1987-02-22' },
  6. { name: 'Peter', city: 'Prague', born: '1936-03-24' },
  7. { name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
  8. { name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
  9. { name: 'Adam', city: 'Trnava', born: '1983-12-01' },
  10. { name: 'Robert', city: 'Bratislava', born: '1935-05-15' },
  11. { name: 'Robert', city: 'Prague', born: '1998-03-14' }
  12. ];
  13. const data = collect(users);
  14. let fval = data.firstWhere('city', 'Bratislava');
  15. console.log(fval);

该示例打印出居住在布拉迪斯拉发的第一位用户。

  1. $ node firstwhere_fun.js
  2. { name: 'Anna', city: 'Bratislava', born: '1973-11-18' }

这是输出。

Collect.js avg()

avg()函数返回集合中所有项目的平均值。

average.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. const data = collect(nums);
  4. console.log(data.avg());

该程序将打印数字数组的平均值。

minmax()

minmax()函数分别返回最小值和最大值。

min_max.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. const data = collect(nums);
  4. console.log(`Minimum: ${data.min()}`);
  5. console.log(`Maximum: ${data.max()}`);

程序打印数字数组的最小值和最大值。

  1. $ node min_max.js
  2. Minimum: 1
  3. Maximum: 10

这是输出。

Collect.js median

median()函数返回中位数。 中位数是数据集的中间值。

median_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. const data = collect(nums);
  4. console.log(data.median());

该示例显示数字数组的中位数。

  1. $ node median.js
  2. 5.5

如果没有中间值,则按照我们的情况计算中间两个值的平均值。

Collect.js each

each()函数遍历集合中的项目,并将每个项目传递给回调。

each_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5];
  3. let sum = 0;
  4. const data = collect(nums);
  5. data.each((item) => {
  6. sum += item;
  7. });
  8. console.log(`The sum of values: ${sum}`);

我们使用each()函数计算值的总和。

  1. $ node each_fun.js
  2. The sum of values: 15

这是输出。

Collect.js eachSpread

eachSpread()函数遍历集合的项目,将每个嵌套的项目值传递给给定的回调。

eachspread_fun.js

  1. const collect = require('collect.js');
  2. const users = [
  3. ['John Doe', 'gardener'], ['Peter Smith', 'programmer'],
  4. ['Lucy Black', 'teacher']
  5. ];
  6. const data = collect(users);
  7. data.eachSpread((user, occupation) => {
  8. console.log(`${user} is a ${occupation}`);
  9. });

该示例使用eachSpread()函数对嵌套数组进行迭代。

  1. $ node eachspread_fun.js
  2. John Doe is a gardener
  3. Peter Smith is a programmer
  4. Lucy Black is a teacher

这是输出。

Collect.js map()

map()函数将给定的回调函数应用于每个元素,从而形成新的修改项集合。

map_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5];
  3. const data = collect(nums);
  4. const tr_data = data.map(e => e * 2);
  5. console.log(tr_data.all());

在示例中,我们通过将每个值乘以 2 来创建修改后的集合。

  1. $ node map_fun.js
  2. [ 2, 4, 6, 8, 10 ]

这是输出。

Collect.js mapInto

mapInto()函数遍历集合并根据元素创建对象。

mapinto_fun.js

  1. const collect = require('collect.js');
  2. const User = function (name, age) {
  3. this.name = name;
  4. this.age = age;
  5. };
  6. const users = [
  7. { name: 'John Doe', age: 34 },
  8. { name: 'Peter Smith', age: 43 },
  9. { name: 'Bruce Long', age: 40 },
  10. { name: 'Lucy White', age: 54 },
  11. ];
  12. const data = collect(users);
  13. const objects = data.mapInto(User);
  14. console.log(objects.all());

在示例中,我们借助mapInto()函数将 JSON 对象文字转换为 JavaScript 对象。

  1. $ node mapinto_fun.js
  2. [ User { name: { name: 'John Doe', age: 34 }, age: 0 },
  3. User { name: { name: 'Peter Smith', age: 43 }, age: 1 },
  4. User { name: { name: 'Bruce Long', age: 40 }, age: 2 },
  5. User { name: { name: 'Lucy White', age: 54 }, age: 3 } ]

这是输出。

Collect.js filter()

filter()函数使用给定的回调函数过滤集合,仅保留那些通过给定的真实性测试的项目。

finter_fun.js

  1. const collect = require('collect.js');
  2. const nums = [-1, 2, -3, 4, -5, 6, 7, 8, -9, 0];
  3. const data = collect(nums);
  4. const filtered = data.filter((val, key) => val > 0);
  5. console.log(filtered.all());

该示例滤除正值。

  1. $ node finter_fun.js
  2. [ 2, 4, 6, 7, 8 ]

这是输出。

  1. $ npm i moment

在下面的示例中,我们还需要moment.js库。

filter_fun2.js

  1. const collect = require('collect.js');
  2. const moment = require('moment');
  3. const users = [
  4. { name: 'John', city: 'London', born: '2001-04-01' },
  5. { name: 'Lenny', city: 'New York', born: '1997-12-11' },
  6. { name: 'Andrew', city: 'Boston', born: '1987-02-22' },
  7. { name: 'Peter', city: 'Prague', born: '1936-03-24' },
  8. { name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
  9. { name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
  10. { name: 'Adam', city: 'Trnava', born: '1983-12-01' },
  11. { name: 'Robert', city: 'Bratislava', born: '1935-05-15' },
  12. { name: 'Robert', city: 'Prague', born: '1998-03-14' }
  13. ];
  14. const data = collect(users);
  15. let res = data.filter((val, key) => getAge(val.born) > 40);
  16. console.log(res.all());
  17. function getAge(dt) {
  18. return moment.duration(moment() - moment(dt, 'YYYY-MM-DD', true)).years();
  19. }

该示例过滤出年龄超过 40 岁的用户。

  1. $ node filter_fun2.js
  2. [ { name: 'Peter', city: 'Prague', born: '1936-03-24' },
  3. { name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
  4. { name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
  5. { name: 'Robert', city: 'Bratislava', born: '1935-05-15' } ]

列表中有四个人大于四十岁。

Collect.js shuffle()

shuffle()函数随机重组集合中的项目。

shuffle.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. const data = collect(nums);
  4. const shuffled = data.shuffle();
  5. console.log(shuffled.all());

该示例重新排列数组。

  1. $ node shuffling.js
  2. [ 6, 4, 3, 7, 5, 10, 1, 9, 8, 2 ]

这是一个示例输出。

Collect.js random()

random()函数从集合中返回一个随机元素。

random_fun.js

  1. const collect = require('collect.js');
  2. let nums = [1, 2, 3, 4, 5, 6, 7, 8];
  3. const data = collect(nums);
  4. let r1 = data.random();
  5. console.log(r1);
  6. let r2 = data.random(2);
  7. console.log(r2.all());

该示例从一个数字数组中选择一个随机值和两个随机值。

  1. $ node random_fun.js
  2. 6
  3. [ 4, 2 ]

这是输出。

Collect.js sortBy()

sortBy()函数通过给定的键对集合进行排序。

sortby_fun.js

  1. const collect = require('collect.js');
  2. const users = [
  3. { name: 'John Doe', occupation: 'gardener' },
  4. { name: 'Adam Forsythe', occupation: 'writer' },
  5. { name: 'Peter Smith', occupation: 'programmer' },
  6. { name: 'Lucy Black', occupation: 'teacher' }
  7. ];
  8. const data = collect(users);
  9. const sorted1 = data.sortBy('name');
  10. console.log(sorted1.all());
  11. const sorted2 = data.sortBy('occupation');
  12. console.log(sorted2.all());

该程序通过提供的键对对象数组进行排序。

  1. $ node sortby_fun.js
  2. [ { name: 'Adam Forsythe', occupation: 'writer' },
  3. { name: 'John Doe', occupation: 'gardener' },
  4. { name: 'Lucy Black', occupation: 'teacher' },
  5. { name: 'Peter Smith', occupation: 'programmer' } ]
  6. [ { name: 'John Doe', occupation: 'gardener' },
  7. { name: 'Peter Smith', occupation: 'programmer' },
  8. { name: 'Lucy Black', occupation: 'teacher' },
  9. { name: 'Adam Forsythe', occupation: 'writer' } ]

数组通过nameoccupation键排序。

nth()

nth()函数返回集合中的每个第 n 个元素。

nth_fun.js

  1. const collect = require('collect.js');
  2. const nums = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
  3. const data = collect(nums);
  4. console.log(data.nth(2).all());
  5. console.log(data.nth(3).all());
  6. console.log(data.nth(4).all());

该示例返回数组的第二,第三和第四个元素。

  1. $ node nth_fun.js
  2. [ 'a', 'c', 'e', 'g' ]
  3. [ 'a', 'd', 'g' ]
  4. [ 'a', 'e' ]

这是输出。

Collect.js chunk()

chunk()函数将集合分成给定大小的较小部分。

chunk_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. const data = collect(nums);
  4. const chunks = data.chunk(4);
  5. console.log(chunks.toArray());

该示例将数组分为包含四个元素的部分。

  1. $ node chunk_fun.js
  2. [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]

这是输出。

  1. node flatten_fun.js
  2. [ 4, 5, 6, 7, 8, 9, 10 ]

这是输出。

Collect.js dif()

dif()函数将一个集合与另一个集合进行比较。 它从原始集合中返回第二个集合中不存在的值。

diff_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4];
  3. const nums2 = [3, 4, 5, 6];
  4. const data = collect(nums);
  5. const data2 = collect(nums2);
  6. const difference = data.diff(data2);
  7. console.log(difference.all());

该示例返回两个数组之间的差。

  1. $ node diff_fun.js
  2. [ 1, 2 ]

这是输出。

Collect.js partition()

partition()函数将集合的元素分为两部分:通过给定条件的元素和不通过给定条件的元素。

partition_fun.js

  1. const collect = require('collect.js');
  2. const nums = [-1, 2, 3, -4, 5, 7, -2];
  3. const data = collect(nums);
  4. const [positive, negative] = data.partition(e => {
  5. return e < 0 && e != 0;
  6. });
  7. console.log(positive.all());
  8. console.log(negative.all());

该示例使用partition函数将正值与负值分开。

  1. $ node partition_fun.js
  2. [ -1, -4, -2 ]
  3. [ 2, 3, 5, 7 ]

这是输出。

Collect.js pluck()

pluck()函数检索给定键的所有值。

pluck_fun.js

  1. const collect = require('collect.js');
  2. const users = [
  3. { name: 'John', city: 'London', born: '2001-04-01' },
  4. { name: 'Lenny', city: 'New York', born: '1997-12-11' },
  5. { name: 'Andrew', city: 'Boston', born: '1987-02-22' },
  6. { name: 'Peter', city: 'Prague', born: '1936-03-24' },
  7. { name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
  8. { name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
  9. { name: 'Adam', city: 'Trnava', born: '1983-12-01' },
  10. { name: 'Robert', city: 'Bratislava', born: '1935-05-15' },
  11. { name: 'Robert', city: 'Prague', born: '1998-03-14' }
  12. ];
  13. let data = collect(users);
  14. let names = data.pluck('name');
  15. console.log(names.all());
  16. let cities = data.pluck('city');
  17. console.log(cities.all());

该示例从users对象的数组中打印所有名称和城市。 由于名称和城市在重复,因此我们使用unique()使其具有唯一性。

  1. $ node pluck_fun.js
  2. [ 'John',
  3. 'Lenny',
  4. 'Andrew',
  5. 'Peter',
  6. 'Anna',
  7. 'Albert',
  8. 'Adam',
  9. 'Robert' ]
  10. [ 'London', 'New York', 'Boston', 'Prague', 'Bratislava', 'Trnava' ]

这是输出。

Collect.js implode()

implode()函数通过给定字符将集合的元素连接在一起。

implode_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. const data = collect(nums);
  4. let output = data.implode('-');
  5. console.log(output);

该示例使用’-‘字符连接元素。

当我们处理对象时,我们需要指定用于连接元素的键。

implode_fun2.js

  1. const collect = require('collect.js');
  2. const users = [
  3. { name: 'John Doe', occupation: 'gardener' },
  4. { name: 'Adam Forsythe', occupation: 'writer' },
  5. { name: 'Peter Smith', occupation: 'programmer' },
  6. { name: 'Lucy Black', occupation: 'teacher' }
  7. ];
  8. const data = collect(users);
  9. let output = data.implode('name', ',');
  10. console.log(output);

该示例将对象users数组中的名称连接在一起。

  1. $ node implode_fun2.js
  2. John Doe,Adam Forsythe,Peter Smith,Lucy Black

这是输出。

Collect.js reduce

reduce函数将集合减小为单个值,将每次迭代的结果传递到后续迭代中。 该函数的第一个参数是累加器或进位,第二个参数是当前元素。

reduce_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 2, 3, 4, 5, 6];
  3. const data = collect(nums);
  4. const val = data.reduce((c, e) => { return e += c });
  5. console.log(val);
  6. const val2 = data.chunk(2).reduce((c, e) => {
  7. return c + e.get(0) * e.get(1)
  8. }, 0);
  9. console.log(val2);

该程序使用reduce()函数来计算总和和值乘积之和。

  1. const val2 = data.chunk(2).reduce((c, e) => {
  2. return c + e.get(0) * e.get(1)
  3. }, 0);

借助chunk()函数,我们计算对的乘积之和:1 * 2 + 3 * 4 + 5 * 6

  1. $ node reduce_fun.js
  2. 21
  3. 44

这是输出。

Collect.js tap

tap函数将集合传递给给定的回调,使我们可以在特定点挂接到集合中,并在不影响集合本身的情况下对项目执行某些操作。

tap_fun.js

  1. const collect = require('collect.js');
  2. const nums = [1, 3, 2, 6, 5, 4];
  3. const data = collect(nums);
  4. const val = data.sort()
  5. .tap((col) => console.log(col.all()))
  6. .chunk(2)
  7. .tap((col) => console.log(col.toArray()))
  8. .reduce((c, e) => c + e.get(0) * e.get(1));
  9. console.log(val);

该示例对集合进行排序,将其分块并最终缩小它。 在此过程中,我们会挂接操作以查看结果。

  1. $ node tap_fun.js
  2. [ 1, 2, 3, 4, 5, 6 ]
  3. [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
  4. 44

这是输出。

every

every函数验证集合中的所有元素均通过给定的真实性测试。

every_fun.js

  1. const collect = require('collect.js');
  2. const words = ['forest', 'wood', 'sky', 'cloud'];
  3. const data = collect(words);
  4. if (data.every(e => e.length > 2)){
  5. console.log('Each word has more than 2 letters');
  6. } else {
  7. console.log('There is at least one word that does not have more than 2 letters');
  8. }

该程序将验证集合中的每个单词是否包含两个以上的字符。

  1. $ node every_fun.js
  2. Each word has more than 2 letters

该集合通过了真相测试。

Collect.js groupBy()

groupBy()函数通过给定的键对集合的项目进行分组。

groupby_fun.js

  1. const collect = require('collect.js');
  2. const users = [
  3. { name: 'John', city: 'London', born: '2001-04-01' },
  4. { name: 'Lenny', city: 'New York', born: '1997-12-11' },
  5. { name: 'Andrew', city: 'Boston', born: '1987-02-22' },
  6. { name: 'Peter', city: 'Prague', born: '1936-03-24' },
  7. { name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
  8. { name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
  9. { name: 'Adam', city: 'Trnava', born: '1983-12-01' },
  10. { name: 'Robert', city: 'Bratislava', born: '1935-05-15' },
  11. { name: 'Robert', city: 'Prague', born: '1998-03-14' }
  12. ];
  13. const data = collect(users);
  14. let cityGroups = data.groupBy('city');
  15. cityGroups.each((group, city) => {
  16. console.log(city);
  17. group.each(e => {
  18. let { name, city, born } = e;
  19. console.log(`${name} ${born}`);
  20. });
  21. });

该示例按城市对用户进行分组。

  1. $ node groupby_fun.js
  2. London
  3. John 2001-04-01
  4. New York
  5. Lenny 1997-12-11
  6. Boston
  7. Andrew 1987-02-22
  8. Prague
  9. Peter 1936-03-24
  10. Robert 1998-03-14
  11. Bratislava
  12. Anna 1973-11-18
  13. Albert 1940-12-11
  14. Robert 1935-05-15
  15. Trnava
  16. Adam 1983-12-01

这是输出。

在本教程中,我们介绍了 Collect.js JavaScript 库。

您可能也对以下相关教程感兴趣: Ramda 教程JSON 服务器教程Moment.js 教程Lodash 教程