Collect.js 教程
最后修改于 2023 年 10 月 18 日
在本文中,我们将展示如何使用 Collect.js 库在 JavaScript 中处理数组和对象。
Collect.js
Collect.js 是一个流畅且方便的包装器,用于处理数组和对象。 它是 Laravel 的 Collections 的一个移植版本。 它包含许多使数据操作更轻松的函数。
Collect.js 帮助程序员编写更简洁、更易于维护的 JavaScript 代码。
Collect.js 安装
首先,我们安装 Collect.js 库。
$ npm init -y $ npm i collect.js
使用 npm 在本地安装 collect.js 库。
collect 函数
我们使用 collect 将 JavaScript 数组转换为集合,并在集合上应用函数。 最后,我们使用 all 或 toArray 将底层数组取回。
Collect.js all vs toArray
all 和 toArray 函数从集合中返回底层数组。 这两个函数的区别在于,如果存在嵌套集合,则 toArray 函数还会将嵌套集合转换为数组。
const collect = require('collect.js');
const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
const data = collect([collect(nums1),
collect(nums2)]);
console.log(data.all());
console.log(data.toArray());
该示例显示了这两个函数的区别。
$ node all_toarray.js
[ Collection { items: [ 1, 2, 3 ] },
Collection { items: [ 4, 5, 6 ] } ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
从输出中我们可以看到,在第二个示例中,嵌套集合被转换为数组。
Collect.js count
count 函数计算集合中元素的数量。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const data = collect(nums);
const nOfElements = data.count();
console.log(`There are ${nOfElements} elements`);
该示例计算数组中值的数量。
$ node count_elements.js Therea are 10 elements
Collect.js unique
unique 函数返回集合中所有唯一项。
const collect = require('collect.js');
const nums = [1, 1, 1, 2, 4, 4, 5];
const data = collect(nums);
const unique_data = data.unique();
console.log(unique_data.all());
该示例打印数组的唯一值。
const unique_data = data.unique();
我们使用 unique 从集合中获取所有唯一值。
console.log(unique_data.all());
all 函数返回集合表示的底层数组。
$ node unique.js [ 1, 2, 4, 5 ]
Collect.js first
first 函数返回集合中通过给定真值测试的第一个元素,或者仅仅是第一个值。
const collect = require('collect.js');
const nums = [1, 2, -3, 4, -5, 6, 7, 8];
const data = collect(nums);
let fval = data.first();
console.log(fval);
let fneg = data.first(e => e < 0);
console.log(fneg);
该示例打印第一个值和第一个负值。
$ node first_fun.js 1 -3
Collect.js firstWhere
firstWhere 函数返回集合中具有给定键/值对的第一个元素。
const collect = require('collect.js');
const users = [
{ name: 'John', city: 'London', born: '2001-04-01' },
{ name: 'Lenny', city: 'New York', born: '1997-12-11' },
{ name: 'Andrew', city: 'Boston', born: '1987-02-22' },
{ name: 'Peter', city: 'Prague', born: '1936-03-24' },
{ name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
{ name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
{ name: 'Adam', city: 'Trnava', born: '1983-12-01' },
{ name: 'Robert', city: 'Bratislava', born: '1935-05-15' },
{ name: 'Robert', city: 'Prague', born: '1998-03-14' }
];
const data = collect(users);
let fval = data.firstWhere('city', 'Bratislava');
console.log(fval);
该示例打印居住在布拉迪斯拉发的第一个用户。
$ node firstwhere_fun.js
{ name: 'Anna', city: 'Bratislava', born: '1973-11-18' }
Collect.js avg
avg 函数返回集合中所有项目的平均值。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const data = collect(nums);
console.log(data.avg());
该程序打印数字数组的平均值。
Collect.js min & max
min 和 max 函数分别返回最小值和最大值。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const data = collect(nums);
console.log(`Minimum: ${data.min()}`);
console.log(`Maximum: ${data.max()}`);
该程序打印数字数组的最小值和最大值。
$ node min_max.js Minimum: 1 Maximum: 10
Collect.js median
median 函数返回中位数。 中位数是数据集的中间值。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const data = collect(nums);
console.log(data.median());
该示例打印数字数组的中位数。
$ node median.js 5.5
如果没有中间值,则计算中间两个值的平均值,就像我们的情况一样。
Collect.js each
each 函数遍历集合中的项目,并将每个项目传递给回调函数。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5];
let sum = 0;
const data = collect(nums);
data.each((item) => {
sum += item;
});
console.log(`The sum of values: ${sum}`);
我们使用 each 函数计算值的总和。
$ node each_fun.js The sum of values: 15
Collect.js eachSpread
eachSpread 函数遍历集合的项目,并将每个嵌套的项目值传递到给定的回调函数中。
const collect = require('collect.js');
const users = [
['John Doe', 'gardener'], ['Peter Smith', 'programmer'],
['Lucy Black', 'teacher']
];
const data = collect(users);
data.eachSpread((user, occupation) => {
console.log(`${user} is a ${occupation}`);
});
该示例使用 eachSpread 函数遍历嵌套数组。
$ node eachspread_fun.js John Doe is a gardener Peter Smith is a programmer Lucy Black is a teacher
Collect.js map
map 函数对每个元素应用给定的回调函数,从而形成一个包含已修改项目的新集合。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5];
const data = collect(nums);
const tr_data = data.map(e => e * 2);
console.log(tr_data.all());
在示例中,我们通过将每个值乘以 2 来创建一个已修改的集合。
$ node map_fun.js [ 2, 4, 6, 8, 10 ]
Collect.js mapInto
mapInto 函数遍历集合并从元素创建对象。
const collect = require('collect.js');
const User = function (name, age) {
this.name = name;
this.age = age;
};
const users = [
{ name: 'John Doe', age: 34 },
{ name: 'Peter Smith', age: 43 },
{ name: 'Bruce Long', age: 40 },
{ name: 'Lucy White', age: 54 },
];
const data = collect(users);
const objects = data.mapInto(User);
console.log(objects.all());
在示例中,我们借助 mapInto 函数将 JSON 对象字面量转换为 JavaScript 对象。
$ node mapinto_fun.js
[ User { name: { name: 'John Doe', age: 34 }, age: 0 },
User { name: { name: 'Peter Smith', age: 43 }, age: 1 },
User { name: { name: 'Bruce Long', age: 40 }, age: 2 },
User { name: { name: 'Lucy White', age: 54 }, age: 3 } ]
Collect.js filter
filter 函数使用给定的回调函数过滤集合,仅保留通过给定真值测试的项目。
const collect = require('collect.js');
const nums = [-1, 2, -3, 4, -5, 6, 7, 8, -9, 0];
const data = collect(nums);
const filtered = data.filter((val, key) => val > 0);
console.log(filtered.all());
该示例过滤掉正值。
$ node finter_fun.js [ 2, 4, 6, 7, 8 ]
$ npm i moment
在下面的示例中,我们还需要 moment.js 库。
const collect = require('collect.js');
const moment = require('moment');
const users = [
{ name: 'John', city: 'London', born: '2001-04-01' },
{ name: 'Lenny', city: 'New York', born: '1997-12-11' },
{ name: 'Andrew', city: 'Boston', born: '1987-02-22' },
{ name: 'Peter', city: 'Prague', born: '1936-03-24' },
{ name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
{ name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
{ name: 'Adam', city: 'Trnava', born: '1983-12-01' },
{ name: 'Robert', city: 'Bratislava', born: '1935-05-15' },
{ name: 'Robert', city: 'Prague', born: '1998-03-14' }
];
const data = collect(users);
let res = data.filter((val, key) => getAge(val.born) > 40);
console.log(res.all());
function getAge(dt) {
return moment.duration(moment() - moment(dt, 'YYYY-MM-DD', true)).years();
}
该示例过滤掉年龄超过四十岁的用户。
$ node filter_fun2.js
[ { name: 'Peter', city: 'Prague', born: '1936-03-24' },
{ name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
{ name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
{ name: 'Robert', city: 'Bratislava', born: '1935-05-15' } ]
列表中有四个人超过四十岁。
Collect.js shuffle
shuffle 函数随机重新组织集合中的项目。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const data = collect(nums);
const shuffled = data.shuffle();
console.log(shuffled.all());
该示例打乱一个数组。
$ node shuffling.js [ 6, 4, 3, 7, 5, 10, 1, 9, 8, 2 ]
Collect.js random
random 函数从集合中返回一个随机元素。
const collect = require('collect.js');
let nums = [1, 2, 3, 4, 5, 6, 7, 8];
const data = collect(nums);
let r1 = data.random();
console.log(r1);
let r2 = data.random(2);
console.log(r2.all());
该示例从数字数组中选取一个随机值和两个随机值。
$ node random_fun.js 6 [ 4, 2 ]
Collect.js sortBy
sortBy 函数按给定的键对集合进行排序。
const collect = require('collect.js');
const users = [
{ name: 'John Doe', occupation: 'gardener' },
{ name: 'Adam Forsythe', occupation: 'writer' },
{ name: 'Peter Smith', occupation: 'programmer' },
{ name: 'Lucy Black', occupation: 'teacher' }
];
const data = collect(users);
const sorted1 = data.sortBy('name');
console.log(sorted1.all());
const sorted2 = data.sortBy('occupation');
console.log(sorted2.all());
该程序按提供的键对对象数组进行排序。
$ node sortby_fun.js
[ { name: 'Adam Forsythe', occupation: 'writer' },
{ name: 'John Doe', occupation: 'gardener' },
{ name: 'Lucy Black', occupation: 'teacher' },
{ name: 'Peter Smith', occupation: 'programmer' } ]
[ { name: 'John Doe', occupation: 'gardener' },
{ name: 'Peter Smith', occupation: 'programmer' },
{ name: 'Lucy Black', occupation: 'teacher' },
{ name: 'Adam Forsythe', occupation: 'writer' } ]
数组按 name 和 occupation 键排序。
Collect.js nth
nth 函数返回集合中的每个第 n 个元素。
const collect = require('collect.js');
const nums = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
const data = collect(nums);
console.log(data.nth(2).all());
console.log(data.nth(3).all());
console.log(data.nth(4).all());
该示例返回数组的每个第二个、第三个和第四个元素。
$ node nth_fun.js [ 'a', 'c', 'e', 'g' ] [ 'a', 'd', 'g' ] [ 'a', 'e' ]
Collect.js chunk
chunk 函数将集合分成给定大小的较小部分。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const data = collect(nums);
const chunks = data.chunk(4);
console.log(chunks.toArray());
该示例将数组分成包含四个元素的几部分。
$ node chunk_fun.js [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]
node flatten_fun.js [ 4, 5, 6, 7, 8, 9, 10 ]
Collect.js difference
dif 函数将集合与另一个集合进行比较。 它返回原始集合中不存在于第二个集合中的值。
const collect = require('collect.js');
const nums = [1, 2, 3, 4];
const nums2 = [3, 4, 5, 6];
const data = collect(nums);
const data2 = collect(nums2);
const difference = data.diff(data2);
console.log(difference.all());
该示例返回两个数组之间的差异。
$ node diff_fun.js [ 1, 2 ]
Collect.js partition
partition 函数将集合的元素分成两部分:通过给定条件和未通过给定条件的元素。
const collect = require('collect.js');
const nums = [-1, 2, 3, -4, 5, 7, -2];
const data = collect(nums);
const [positive, negative] = data.partition(e => {
return e < 0 && e != 0;
});
console.log(positive.all());
console.log(negative.all());
该示例使用 partition 函数将正值与负值分开。
$ node partition_fun.js [ -1, -4, -2 ] [ 2, 3, 5, 7 ]
Collect.js pluck
pluck 函数检索给定键的所有值。
const collect = require('collect.js');
const users = [
{ name: 'John', city: 'London', born: '2001-04-01' },
{ name: 'Lenny', city: 'New York', born: '1997-12-11' },
{ name: 'Andrew', city: 'Boston', born: '1987-02-22' },
{ name: 'Peter', city: 'Prague', born: '1936-03-24' },
{ name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
{ name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
{ name: 'Adam', city: 'Trnava', born: '1983-12-01' },
{ name: 'Robert', city: 'Bratislava', born: '1935-05-15' },
{ name: 'Robert', city: 'Prague', born: '1998-03-14' }
];
let data = collect(users);
let names = data.pluck('name');
console.log(names.all());
let cities = data.pluck('city');
console.log(cities.all());
该示例从 users 对象数组中打印所有名称和城市。 由于名称和城市是重复的,我们使用 unique 使它们唯一。
$ node pluck_fun.js
[ 'John',
'Lenny',
'Andrew',
'Peter',
'Anna',
'Albert',
'Adam',
'Robert' ]
[ 'London', 'New York', 'Boston', 'Prague', 'Bratislava', 'Trnava' ]
Collect.js implode
implode 函数通过给定的字符连接集合的元素。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const data = collect(nums);
let output = data.implode('-');
console.log(output);
该示例使用 '-' 字符连接元素。
当我们处理对象时,我们需要指定用于连接元素的键。
const collect = require('collect.js');
const users = [
{ name: 'John Doe', occupation: 'gardener' },
{ name: 'Adam Forsythe', occupation: 'writer' },
{ name: 'Peter Smith', occupation: 'programmer' },
{ name: 'Lucy Black', occupation: 'teacher' }
];
const data = collect(users);
let output = data.implode('name', ',');
console.log(output);
该示例连接来自 users 对象数组的名称。
$ node implode_fun2.js John Doe,Adam Forsythe,Peter Smith,Lucy Black
Collect.js reduce
reduce 函数将集合减少为单个值,将每次迭代的结果传递到后续迭代中。 函数的第一个参数是累加器或进位,第二个参数是当前元素。
const collect = require('collect.js');
const nums = [1, 2, 3, 4, 5, 6];
const data = collect(nums);
const val = data.reduce((c, e) => { return e += c });
console.log(val);
const val2 = data.chunk(2).reduce((c, e) => {
return c + e.get(0) * e.get(1)
}, 0);
console.log(val2);
该程序使用 reduce 函数计算值的总和以及值的乘积的总和。
const val2 = data.chunk(2).reduce((c, e) => {
return c + e.get(0) * e.get(1)
}, 0);
借助 chunk 函数,我们计算对的乘积之和:1*2 + 3*4 + 5*6。
$ node reduce_fun.js 21 44
Collect.js tap
tap 函数将集合传递给给定的回调函数,允许我们钩入集合的特定点并对项目执行操作,同时不影响集合本身。
const collect = require('collect.js');
const nums = [1, 3, 2, 6, 5, 4];
const data = collect(nums);
const val = data.sort()
.tap((col) => console.log(col.all()))
.chunk(2)
.tap((col) => console.log(col.toArray()))
.reduce((c, e) => c + e.get(0) * e.get(1));
console.log(val);
该示例对集合进行排序、分块,最后进行归约。 在此过程中,我们钩入操作以查看结果。
$ node tap_fun.js [ 1, 2, 3, 4, 5, 6 ] [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] 44
Collect.js every
every 函数验证集合的所有元素是否通过给定的真值测试。
const collect = require('collect.js');
const words = ['forest', 'wood', 'sky', 'cloud'];
const data = collect(words);
if (data.every(e => e.length > 2)){
console.log('Each word has more than 2 letters');
} else {
console.log('There is at least one word that does not have more than 2 letters');
}
该程序验证集合中的每个单词是否包含两个以上的字符。
$ node every_fun.js Each word has more than 2 letters
集合通过真值测试。
Collect.js groupBy
groupBy 函数按给定的键对集合的项目进行分组。
const collect = require('collect.js');
const users = [
{ name: 'John', city: 'London', born: '2001-04-01' },
{ name: 'Lenny', city: 'New York', born: '1997-12-11' },
{ name: 'Andrew', city: 'Boston', born: '1987-02-22' },
{ name: 'Peter', city: 'Prague', born: '1936-03-24' },
{ name: 'Anna', city: 'Bratislava', born: '1973-11-18' },
{ name: 'Albert', city: 'Bratislava', born: '1940-12-11' },
{ name: 'Adam', city: 'Trnava', born: '1983-12-01' },
{ name: 'Robert', city: 'Bratislava', born: '1935-05-15' },
{ name: 'Robert', city: 'Prague', born: '1998-03-14' }
];
const data = collect(users);
let cityGroups = data.groupBy('city');
cityGroups.each((group, city) => {
console.log(city);
group.each(e => {
let { name, city, born } = e;
console.log(`${name} ${born}`);
});
});
该示例按城市对用户进行分组。
$ node groupby_fun.js London John 2001-04-01 New York Lenny 1997-12-11 Boston Andrew 1987-02-22 Prague Peter 1936-03-24 Robert 1998-03-14 Bratislava Anna 1973-11-18 Albert 1940-12-11 Robert 1935-05-15 Trnava Adam 1983-12-01
来源
在本文中,我们介绍了 Collect.js JavaScript 库。