53.md 18.9 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8
# Collect.js 教程

> 原文: [http://zetcode.com/javascript/collectjs/](http://zetcode.com/javascript/collectjs/)

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

## Collect.js

W
wizardforcel 已提交
9
Collect.js 是用于处理数组和对象的流畅,便捷的包装器。 它是 Laravel 集合的接口。 它包含许多使数据处理更加容易的函数。
W
wizardforcel 已提交
10 11 12 13 14 15 16

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

## Collect.js 安装

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

W
wizardforcel 已提交
17
```js
W
wizardforcel 已提交
18 19 20 21 22 23 24
$ npm init
$ npm i collect.js

```

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

W
wizardforcel 已提交
25
## `collect()`函数
W
wizardforcel 已提交
26 27 28

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

W
wizardforcel 已提交
29
## Collect.js `all()`与`toArray`
W
wizardforcel 已提交
30 31 32 33 34

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

`all_toarray.js`

W
wizardforcel 已提交
35
```js
W
wizardforcel 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48
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());

```

W
wizardforcel 已提交
49
该示例显示了两个函数之间的区别。
W
wizardforcel 已提交
50

W
wizardforcel 已提交
51
```js
W
wizardforcel 已提交
52 53 54 55 56 57 58 59 60
$ node all_toarray.js
[ Collection { items: [ 1, 2, 3 ] },
    Collection { items: [ 4, 5, 6 ] } ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

```

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

W
wizardforcel 已提交
61
## Collect.js `count()`
W
wizardforcel 已提交
62 63 64 65 66

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

`count_elements.js`

W
wizardforcel 已提交
67
```js
W
wizardforcel 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81
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`);

```

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

W
wizardforcel 已提交
82
```js
W
wizardforcel 已提交
83 84 85 86 87
$ node count_elements.js
Therea are 10 elements

```

W
wizardforcel 已提交
88
## Collect.js `unique()`
W
wizardforcel 已提交
89 90 91 92 93

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

`unique.js`

W
wizardforcel 已提交
94
```js
W
wizardforcel 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107
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()); 

```

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

W
wizardforcel 已提交
108
```js
W
wizardforcel 已提交
109 110 111 112 113 114
const unique_data = data.unique();

```

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

W
wizardforcel 已提交
115
```js
W
wizardforcel 已提交
116 117 118 119 120 121
console.log(unique_data.all()); 

```

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

W
wizardforcel 已提交
122
```js
W
wizardforcel 已提交
123 124 125 126 127 128 129
$ node unique.js
[ 1, 2, 4, 5 ]

```

这是输出。

W
wizardforcel 已提交
130
## `first`
W
wizardforcel 已提交
131 132 133 134 135

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

`first_fun.js`

W
wizardforcel 已提交
136
```js
W
wizardforcel 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
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);

```

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

W
wizardforcel 已提交
152
```js
W
wizardforcel 已提交
153 154 155 156 157 158 159 160
$ node first_fun.js
1
-3

```

这是输出。

W
wizardforcel 已提交
161
## `firstWhere`
W
wizardforcel 已提交
162 163 164 165 166

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

`firstwhere_fun.js`

W
wizardforcel 已提交
167
```js
W
wizardforcel 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
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);

```

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

W
wizardforcel 已提交
191
```js
W
wizardforcel 已提交
192 193 194 195 196 197 198
$ node firstwhere_fun.js
{ name: 'Anna', city: 'Bratislava', born: '1973-11-18' }

```

这是输出。

W
wizardforcel 已提交
199
## Collect.js `avg()`
W
wizardforcel 已提交
200 201 202 203 204

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

`average.js`

W
wizardforcel 已提交
205
```js
W
wizardforcel 已提交
206 207 208 209 210 211 212 213 214 215 216 217
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());

```

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

W
wizardforcel 已提交
218
## `min`和`max()`
W
wizardforcel 已提交
219 220 221 222 223

`min``max()`函数分别返回最小值和最大值。

`min_max.js`

W
wizardforcel 已提交
224
```js
W
wizardforcel 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237
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()}`);

```

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

W
wizardforcel 已提交
238
```js
W
wizardforcel 已提交
239 240 241 242 243 244 245 246
$ node min_max.js
Minimum: 1
Maximum: 10

```

这是输出。

W
wizardforcel 已提交
247
## Collect.js `median`
W
wizardforcel 已提交
248 249 250 251 252

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

`median_fun.js`

W
wizardforcel 已提交
253
```js
W
wizardforcel 已提交
254 255 256 257 258 259 260 261 262 263 264 265
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());

```

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

W
wizardforcel 已提交
266
```js
W
wizardforcel 已提交
267 268 269 270 271 272 273
$ node median.js
5.5

```

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

W
wizardforcel 已提交
274
## Collect.js `each`
W
wizardforcel 已提交
275 276 277 278 279

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

`each_fun.js`

W
wizardforcel 已提交
280
```js
W
wizardforcel 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
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()`函数计算值的总和。

W
wizardforcel 已提交
298
```js
W
wizardforcel 已提交
299 300 301 302 303 304 305
$ node each_fun.js
The sum of values: 15

```

这是输出。

W
wizardforcel 已提交
306
## Collect.js `eachSpread`
W
wizardforcel 已提交
307 308 309 310 311

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

`eachspread_fun.js`

W
wizardforcel 已提交
312
```js
W
wizardforcel 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
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()`函数对嵌套数组进行迭代。

W
wizardforcel 已提交
330
```js
W
wizardforcel 已提交
331 332 333 334 335 336 337 338 339
$ node eachspread_fun.js
John Doe is a gardener
Peter Smith is a programmer
Lucy Black is a teacher

```

这是输出。

W
wizardforcel 已提交
340
## Collect.js `map()`
W
wizardforcel 已提交
341 342 343 344 345

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

`map_fun.js`

W
wizardforcel 已提交
346
```js
W
wizardforcel 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360
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 来创建修改后的集合。

W
wizardforcel 已提交
361
```js
W
wizardforcel 已提交
362 363 364 365 366 367 368
$ node  map_fun.js
[ 2, 4, 6, 8, 10 ]

```

这是输出。

W
wizardforcel 已提交
369
## Collect.js `mapInto`
W
wizardforcel 已提交
370 371 372 373 374

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

`mapinto_fun.js`

W
wizardforcel 已提交
375
```js
W
wizardforcel 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
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 对象。

W
wizardforcel 已提交
400
```js
W
wizardforcel 已提交
401 402 403 404 405 406 407 408 409 410
$ 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 } ]

```

这是输出。

W
wizardforcel 已提交
411
## Collect.js `filter()`
W
wizardforcel 已提交
412 413 414 415 416

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

`finter_fun.js`

W
wizardforcel 已提交
417
```js
W
wizardforcel 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430
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());

```

该示例滤除正值。

W
wizardforcel 已提交
431
```js
W
wizardforcel 已提交
432 433 434 435 436 437 438
$ node finter_fun.js
[ 2, 4, 6, 7, 8 ]

```

这是输出。

W
wizardforcel 已提交
439
```js
W
wizardforcel 已提交
440 441 442 443 444 445 446 447
$ npm i moment

```

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

`filter_fun2.js`

W
wizardforcel 已提交
448
```js
W
wizardforcel 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
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();
}

```

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

W
wizardforcel 已提交
478
```js
W
wizardforcel 已提交
479 480 481 482 483 484 485 486 487 488
$ 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' } ]

```

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

W
wizardforcel 已提交
489
## Collect.js `shuffle()`
W
wizardforcel 已提交
490

W
wizardforcel 已提交
491
`shuffle()`函数随机重组集合中的项目。
W
wizardforcel 已提交
492 493 494

`shuffle.js`

W
wizardforcel 已提交
495
```js
W
wizardforcel 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509
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());

```

该示例重新排列数组。

W
wizardforcel 已提交
510
```js
W
wizardforcel 已提交
511 512 513 514 515 516 517
$ node shuffling.js
[ 6, 4, 3, 7, 5, 10, 1, 9, 8, 2 ]

```

这是一个示例输出。

W
wizardforcel 已提交
518
## Collect.js `random()`
W
wizardforcel 已提交
519 520 521 522 523

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

`random_fun.js`

W
wizardforcel 已提交
524
```js
W
wizardforcel 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
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());

```

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

W
wizardforcel 已提交
541
```js
W
wizardforcel 已提交
542 543 544 545 546 547 548 549
$ node random_fun.js
6
[ 4, 2 ]

```

这是输出。

W
wizardforcel 已提交
550
## Collect.js `sortBy()`
W
wizardforcel 已提交
551

W
wizardforcel 已提交
552
`sortBy()`函数通过给定的键对集合进行排序。
W
wizardforcel 已提交
553 554 555

`sortby_fun.js`

W
wizardforcel 已提交
556
```js
W
wizardforcel 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
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());

```

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

W
wizardforcel 已提交
578
```js
W
wizardforcel 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592
$ 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`键排序。

W
wizardforcel 已提交
593
## `nth()`
W
wizardforcel 已提交
594 595 596 597 598

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

`nth_fun.js`

W
wizardforcel 已提交
599
```js
W
wizardforcel 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613
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());

```

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

W
wizardforcel 已提交
614
```js
W
wizardforcel 已提交
615 616 617 618 619 620 621 622 623
$ node nth_fun.js
[ 'a', 'c', 'e', 'g' ]
[ 'a', 'd', 'g' ]
[ 'a', 'e' ]

```

这是输出。

W
wizardforcel 已提交
624
## Collect.js `chunk()`
W
wizardforcel 已提交
625 626 627 628 629

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

`chunk_fun.js`

W
wizardforcel 已提交
630
```js
W
wizardforcel 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643
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());

```

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

W
wizardforcel 已提交
644
```js
W
wizardforcel 已提交
645 646 647 648 649 650 651
$ node chunk_fun.js
[ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]

```

这是输出。

W
wizardforcel 已提交
652
```js
W
wizardforcel 已提交
653 654 655 656 657 658 659
node flatten_fun.js
[ 4, 5, 6, 7, 8, 9, 10 ]

```

这是输出。

W
wizardforcel 已提交
660
## Collect.js `dif()`
W
wizardforcel 已提交
661

W
wizardforcel 已提交
662
`dif()`函数将一个集合与另一个集合进行比较。 它从原始集合中返回第二个集合中不存在的值。
W
wizardforcel 已提交
663 664 665

`diff_fun.js`

W
wizardforcel 已提交
666
```js
W
wizardforcel 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
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());

```

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

W
wizardforcel 已提交
683
```js
W
wizardforcel 已提交
684 685 686 687 688 689 690
$ node diff_fun.js
[ 1, 2 ]

```

这是输出。

W
wizardforcel 已提交
691
## Collect.js `partition()`
W
wizardforcel 已提交
692 693 694 695 696

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

`partition_fun.js`

W
wizardforcel 已提交
697
```js
W
wizardforcel 已提交
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
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`函数将正值与负值分开。

W
wizardforcel 已提交
715
```js
W
wizardforcel 已提交
716 717 718 719 720 721 722 723
$ node partition_fun.js
[ -1, -4, -2 ]
[ 2, 3, 5, 7 ]

```

这是输出。

W
wizardforcel 已提交
724
## Collect.js `pluck()`
W
wizardforcel 已提交
725 726 727 728 729

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

`pluck_fun.js`

W
wizardforcel 已提交
730
```js
W
wizardforcel 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
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()`使其具有唯一性。

W
wizardforcel 已提交
757
```js
W
wizardforcel 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
$ node pluck_fun.js
[ 'John',
    'Lenny',
    'Andrew',
    'Peter',
    'Anna',
    'Albert',
    'Adam',
    'Robert' ]
[ 'London', 'New York', 'Boston', 'Prague', 'Bratislava', 'Trnava' ]

```

这是输出。

W
wizardforcel 已提交
773
## Collect.js `implode()`
W
wizardforcel 已提交
774 775 776 777 778

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

`implode_fun.js`

W
wizardforcel 已提交
779
```js
W
wizardforcel 已提交
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
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);

```

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

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

`implode_fun2.js`

W
wizardforcel 已提交
797
```js
W
wizardforcel 已提交
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
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`数组中的名称连接在一起。

W
wizardforcel 已提交
816
```js
W
wizardforcel 已提交
817 818 819 820 821 822 823
$ node implode_fun2.js
John Doe,Adam Forsythe,Peter Smith,Lucy Black

```

这是输出。

W
wizardforcel 已提交
824
## Collect.js `reduce`
W
wizardforcel 已提交
825 826 827 828 829

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

`reduce_fun.js`

W
wizardforcel 已提交
830
```js
W
wizardforcel 已提交
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
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);

```

W
wizardforcel 已提交
848
该程序使用`reduce()`函数来计算总和和值乘积之和。
W
wizardforcel 已提交
849

W
wizardforcel 已提交
850
```js
W
wizardforcel 已提交
851 852 853 854 855 856
const val2 = data.chunk(2).reduce((c, e) => { 
    return c + e.get(0) * e.get(1) 
}, 0);

```

W
wizardforcel 已提交
857
借助`chunk()`函数,我们计算对的乘积之和:`1 * 2 + 3 * 4 + 5 * 6`
W
wizardforcel 已提交
858

W
wizardforcel 已提交
859
```js
W
wizardforcel 已提交
860 861 862 863 864 865 866 867
$ node reduce_fun.js
21
44

```

这是输出。

W
wizardforcel 已提交
868
## Collect.js `tap`
W
wizardforcel 已提交
869 870 871 872 873

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

`tap_fun.js`

W
wizardforcel 已提交
874
```js
W
wizardforcel 已提交
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
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);

```

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

W
wizardforcel 已提交
892
```js
W
wizardforcel 已提交
893 894 895 896 897 898 899 900 901
$ node tap_fun.js
[ 1, 2, 3, 4, 5, 6 ]
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
44

```

这是输出。

W
wizardforcel 已提交
902
## `every`
W
wizardforcel 已提交
903 904 905 906 907

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

`every_fun.js`

W
wizardforcel 已提交
908
```js
W
wizardforcel 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
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');
}

```

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

W
wizardforcel 已提交
927
```js
W
wizardforcel 已提交
928 929 930 931 932 933 934
$ node every_fun.js
Each word has more than 2 letters

```

该集合通过了真相测试。

W
wizardforcel 已提交
935
## Collect.js `groupBy()`
W
wizardforcel 已提交
936

W
wizardforcel 已提交
937
`groupBy()`函数通过给定的键对集合的项目进行分组。
W
wizardforcel 已提交
938 939 940

`groupby_fun.js`

W
wizardforcel 已提交
941
```js
W
wizardforcel 已提交
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
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}`);
    });
});

```

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

W
wizardforcel 已提交
975
```js
W
wizardforcel 已提交
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
$ 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 库。

W
wizardforcel 已提交
999
您可能也对以下相关教程感兴趣: [Ramda 教程](/javascript/ramda/)[JSON 服务器教程](/javascript/jsonserver/)[Moment.js 教程](/javascript/momentjs/)[Lodash 教程](/javascript/lodash/)