17c9d34755d43dc042c343a80febbefa9ce24978
[platform/framework/web/crosswalk-tizen.git] /
1 # array #
2
3 Array utilities.
4
5
6
7
8 ## append(arr1, arr2):Array
9
10 Appends an array to the end of the other.
11 The first array will be modified and will contain the appended items.
12
13 See: [`union()`](#union), [`combine()`](#combine)
14
15 ```js
16 var foo = ['a', 'b'],
17     bar = ['b', 'd'];
18
19 append(foo, bar); // ['a', 'b', 'b', 'd']
20 ```
21
22
23
24 ## collect(arr, callback, [thisObj]):Array
25
26 Maps the items in `arr` and concatenates the resulting arrays.
27
28 See: [`map()`](#map)
29
30 ```js
31 collect([1, 2, 3], function(val) {
32     return [val, val % 2];
33 }); // [1, 1, 2, 0, 3, 1];
34
35 collect(['a', 'bb', ''], function(val) {
36     return val.split('');
37 }); // ['a', 'b', 'b']
38 ```
39
40 It also supports a shorthand syntax:
41
42 ```js
43 var items = [{ a: [1] }, { b: 'foo' }, { a: [2, 3] }];
44 collect(items, 'a'); // [1, 2, 3];
45 ```
46
47
48
49 ## combine(arr1, arr2):Array
50
51 Combines an array with all the items of another.
52 The first array will be modified and will contain the combined items.
53 Does not allow duplicates and is case and type sensitive.
54
55 See: [`union()`](#union), [`append()`](#append)
56
57 ```js
58 var foo = ['a', 'b'],
59     bar = ['b', 'd'];
60
61 combine(foo, bar); // ['a', 'b', 'd']
62 ```
63
64
65
66 ## compact(arr):Array
67
68 Returns a new Array without any `null` or `undefined` values. Note that it will
69 keep empty strings and other falsy values (simillar to Ruby Array#compact).
70
71 ```js
72 var arr = [0, 1, null, false, '', 'foo', undefined, 'bar'];
73 compact(arr); // [0, 1, false, '', 'foo', 'bar'];
74 ```
75
76
77
78 ## contains(arr, value):Boolean
79
80 Checks if Array contains value. Alias to `indexOf(arr, val) !== -1`.
81
82 ```js
83 var arr = [1, 2, 3];
84 contains(arr, 2);      // true
85 contains(arr, 'foo');  // false
86 ```
87
88
89
90 ## difference(...arrs):Array
91
92 Return a new Array with elements that aren't present in the other Arrays
93 besides the first one.
94
95 Works like [Python set#difference](http://docs.python.org/library/stdtypes.html#set.difference).
96
97 It will remove duplicates.
98
99 See: [`xor()`](#xor), [`intersection()`](#intersection)
100
101 ```js
102 var a = ['a', 'b', 1];
103 var b = ['c', 1];
104 difference(a, b); // ['a', 'b']
105 ```
106
107
108 ## equals(a, b, [compare]):Boolean
109
110 Checks if both arrays are equal.
111
112 ```js
113 equals([1, 2], [1, 2]); // true
114 equals([2, 4], [1, 2]); // false
115 ```
116
117 By default it uses the [lang/is](lang.html#is) as the `compare` function but
118 you can pass a custom function to change the behavior.
119
120 ```js
121 function loose(a, b) {
122     return a == b;
123 }
124 equals(['1', 2], [1, 2], loose); // true
125 ```
126
127 See: [object/equals](object.html#equals), [lang/deepEquals](lang.html#deepEquals)
128
129
130
131 ## every(arr, callback, [thisObj]):Array
132
133 Crossbrowser `Array.every()`.
134
135 Tests whether all elements in the array pass the test implemented by the provided function.
136
137 It differs from ES5 since it will also loop over sparse items in the array to
138 normalize the behavior across browsers (avoid inconsistencies).
139
140 ```js
141 var items = [1, 'foo', 'bar'];
142 every(items, isString);   // false
143 every(items, isFunction); // false
144 every(items, function(val, key, arr){
145     return val != null;
146 }); // true
147 ```
148
149 more info at [MDN Array#every](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every)
150
151 It also supports a shorthand syntax:
152
153 ```js
154 var items = [{id:1, active:true}, {id:3, active:true}, {id:8, active:true}];
155 // all items with `id === 8`
156 every(items, {id:8}); // false
157 // `active` is truthy on all items
158 every(items, 'active'); // true
159 ```
160
161
162
163 ## filter(arr, callback, [thisObj]):Array
164
165 Crossbrowser `Array.filter()`.
166
167 Creates a new array with all elements that pass the callback test.
168
169 It differs from ES5 since it will also loop over sparse items in the array to
170 normalize the behavior across browsers (avoid inconsistencies).
171
172 ```js
173 var nums = [1, 2, 3, 4, 5, 6];
174 var oddNumbers = filter(nums, function(val, key, arr){
175     return (val % 2) !== 0;
176 });
177 // > [1, 3, 5]
178 ```
179
180 more info at [MDN Array#filter](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter)
181
182 Filter also supports shorthand notation:
183
184 ```js
185 var users = [
186     {name:'john', surname:'connor', beard:false},
187     {name:'john', surname:'doe', beard:true},
188     {name:'jane', surname:'doe', beard:false}
189 ];
190 // filter item that matches all properties/values pairs
191 filter(arr, {name:'john', beard:false});
192 // > [{name:'john', surnname:'connor', beard:false}]
193 // items where 'beard' is a truthy value
194 filter(arr, 'beard');
195 // > [{name:'john', surnname:'doe', beard:true}]
196 ```
197
198 See [`reject()`](#reject)
199
200
201
202 ## find(arr, callback, [thisObj]):*
203
204 Loops through all the items in the Array and returns the first one that passes
205 a truth test (callback).
206
207 ```js
208 var arr = [123, {a:'b'}, 'foo', 'bar'];
209 find(arr, isString); // "foo"
210 find(arr, isNumber); // 123
211 find(arr, isObject); // {a:'b'}
212 ```
213
214 Find also supports shorthand notation:
215
216 ```js
217 var users = [
218     {name:'john', surname:'connor', beard:false},
219     {name:'john', surname:'doe', beard:true}
220 ];
221 // first item that matches all properties/values pairs
222 find(arr, {name:'john'}); // {name:'john', surnname:'connor', beard:false}
223 // first item where 'beard' is a truthy value
224 find(arr, 'beard'); // {name:'john', surnname:'doe', beard:true}
225 ```
226
227 See: [findIndex()](#findIndex), [findLast()](#findLast),
228 [findLastIndex()](#findLastIndex)
229
230
231
232 ## findLast(arr, callback, [thisObj]):*
233
234 Loops through all the items in the Array (starting from last item) and returns
235 the first one that passes a truth test (callback).
236
237 ```js
238 var arr = [123, {a:'b'}, 'foo', 'bar'];
239 findLast(arr, isString); // "bar"
240 findLast(arr, isNumber); // 123
241 findLast(arr, isObject); // {a:'b'}
242 ```
243
244 `findLast` also supports shorthand notation:
245
246 ```js
247 var users = [
248     {name:'john', surname:'connor', beard:false},
249     {name:'john', surname:'doe', beard:true}
250 ];
251 // last item that matches all properties/values pairs
252 findLast(arr, {name:'john'}); // {name:'john', surnname:'doe', beard:true}
253 // last item where 'beard' is a truthy value
254 findLast(arr, 'beard'); // {name:'john', surnname:'doe', beard:true}
255 ```
256
257 See: [find()](#find), [findIndex()](#findIndex),
258 [findLastIndex()](#findLastIndex)
259
260
261
262 ## findIndex(arr, iterator, [thisObj]):Number
263
264 Loops through the items in the Array and returns the index of the first one
265 that passes a truth test (callback).
266
267 Returns `-1` if no item was found that passes the truth test.
268
269 ```js
270 var arr = [1, { a: 1 }, 'foo', 'bar'];
271 findIndex(arr, isString); // 2
272 findIndex(arr, isNumber); // 0
273 findIndex(arr, isObject); // 1
274 findIndex(arr, isRegExp); // -1
275 ```
276
277 `findIndex` also supports shorthand notation:
278
279 ```js
280 var pets = [
281     { pet: 'dog', name: 'Sam' },
282     { pet: 'dog', name: 'Maggie' }
283 ];
284
285 findIndex(pets, { pet: 'dog' }); // 0
286 findIndex(pets, { name: 'Maggie' }); // 1
287 ```
288
289 See: [find()](#find), [findLastIndex()](#findLastIndex)
290
291
292
293 ## findLastIndex(arr, iterator, [thisObj]):Number
294
295 Loops through the items in the Array on the reverse order and returns the index
296 of the first one that passes a truth test (callback).
297
298 Returns `-1` if no item was found that passes the truth test.
299
300 ```js
301 var arr = [1, { a: 1 }, 'foo', 'bar'];
302 findLastIndex(arr, isString); // 3
303 findLastIndex(arr, isNumber); // 0
304 findLastIndex(arr, isObject); // 1
305 findLastIndex(arr, isRegExp); // -1
306 ```
307
308 `findLastndex` also supports shorthand notation:
309
310 ```js
311 var pets = [
312     { pet: 'dog', name: 'Sam' },
313     { pet: 'dog', name: 'Maggie' }
314 ];
315
316 findLastIndex(pets, { pet: 'dog' }); // 1
317 findLastIndex(pets, { name: 'Sam' }); // 0
318 ```
319
320 See: [find()](#find), [findIndex()](#findIndex)
321
322
323
324 ## flatten(arr, [level]):Array
325
326 Recursively flattens an array. A new array containing all the elements is
327 returned. If `level` is specified, it will only flatten up to that level.
328
329 ### Example
330
331 ```js
332 flatten([1, [2], [3, [4, 5]]]);
333 // > [1, 2, 3, 4, 5]
334 flatten([1, [2], [3, [4, 5]]], 1);
335 // > [1, 2, 3, [4, 5]]
336 ```
337
338
339
340 ## forEach(arr, callback, [thisObj]):void
341
342 Crossbrowser `Array.forEach()`.
343
344 It allows exiting the iteration early by returning `false` on the callback.
345
346 It differs from ES5 since it will also loop over sparse items in the array to
347 normalize the behavior across browsers (avoid inconsistencies).
348
349 ```js
350 var items = ['foo', 'bar', 'lorem', 'ipsum'];
351 forEach(items, function(val, key, arr){
352     console.log(key +' : '+ val);
353     if (val === 'lorem') {
354         // stop iteration (break)
355         return false;
356     }
357 });
358 ```
359
360 more info at [MDN Array#forEach](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach)
361
362
363
364 ## groupBy(arr, [categorize=identity], [thisObj]):Object
365
366 Groups array elements by the `key` returned from the `categorize` function.
367
368 It will use the [function/identity](function.html#identity) as the default
369 `categorize` function.
370
371 ```js
372 var items = ['lorem', 'ipsum', 'foo', 'bar', 'baz'];
373 groupBy(items, function(val) { return val.length });
374 // > {'3': ['foo', 'bar', 'baz'], '5': ['lorem', 'ipsum']}
375 ```
376
377
378
379 ## indexOf(arr, item, [fromIndex]):Number
380
381 Crossbrowser `Array.indexOf()`.
382
383 It differs from ES5 since it will also loop over sparse items in the array to
384 normalize the behavior across browsers (avoid inconsistencies).
385
386 more info at [MDN Array#indexOf](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf)
387
388
389
390
391 ## insert(arr, ...items):Number
392
393 Push items into array only if they aren't contained by it. Returns the new
394 `length` of the array.
395
396 See: [`remove()`](#remove), [`removeAll()`](#removeAll),
397 [`contains()`](#contains)
398
399 ```js
400 var arr = ['a', 'b'];
401 insert(arr, 'a');       // 2 : ['a', 'b']
402 insert(arr, 'c');       // 3 : ['a', 'b', 'c']
403 insert(arr, 1, 2, 'b'); // 5 : ['a', 'b', 'c', 1, 2]
404 ```
405
406
407
408 ## intersection(...arrs):Array
409
410 Return a new Array with elements common to all Arrays.
411
412 Similar to Python set#intersection and underscore.js intersection.
413
414 It will remove duplicates.
415
416 See: [`difference()`](#difference), [`xor()`](#xor)
417
418 ```js
419 var a = ['a', 'b', 1],
420     b = ['c', 1],
421     c = [1, 2, 3];
422 intersection(a, b, c); // [1]
423 ```
424
425
426
427 ## invoke(arr, methodName[, ...args]):Array
428
429 Call `methodName` on each item of the array passing custom arguments if needed.
430
431 ```js
432 invoke([[3,2,1], [9,5,2]], 'sort'); // [[1,2,3], [2,5,9]]
433 ```
434
435
436
437 ## join(arr, [separator]):String
438
439 Joins the strings in `arr`, inserting `separator` between each value.
440
441 This ignores null values and empty strings that are in the array. `separator`
442 defaults to an empty string. This will convert all non-string objects in the
443 array to a string.
444
445 ### Example
446
447 ```js
448 join(['a', 'b', 'c']); // 'abc'
449 join(['foo', 'bar'], ', '); // 'foo, bar'
450 join([null, 'foo', '', 'bar', undefined], ':'); // 'foo:bar'
451 ```
452
453
454 ## last(arr):*
455
456 Returns the last element of an array without modifying the array.
457
458
459 ```js
460 last( [1, 2, 3, 4] ) // > 4
461 last( ['foo', 'bar'] ) // > 'bar'
462 ```
463
464
465 ## lastIndexOf(arr, item, [fromIndex]):Number
466
467 Crossbrowser `Array.lastIndexOf()`.
468
469 It differs from ES5 since it will also loop over sparse items in the array to
470 normalize the behavior across browsers (avoid inconsistencies).
471
472 more info at [MDN Array#lastIndexOf](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf)
473
474
475
476 ## map(arr, callback, [thisObj]]):Array
477
478 Crossbrowser `Array.map()`.
479
480 Creates a new array with the results of calling a provided function on every
481 element in this array.
482
483 It differs from ES5 since it will also loop over sparse items in the array to
484 normalize the behavior across browsers (avoid inconsistencies).
485
486 See: [`collect()`](#collect)
487
488 ```js
489 var nums = [1,2,3,4];
490 var double = map(nums, function(val, key, arr){
491     return val * 2;
492 });
493 // > [2, 4, 6, 8]
494 ```
495
496 more info at [MDN Array#map](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map)
497
498 It also supports a shorthand notation which can be used to achieve same result
499 as [`array/pluck`](#pluck):
500
501 ```js
502 var src = ['lorem', 'ipsum', 'foo', 'amet'];
503 // grab the "length" property of all items
504 var lengths = map(src, 'length'); // [5, 5, 3, 4]
505 ```
506
507
508
509 ## max(arr, [iterator], [thisObj]):*
510
511 Returns maximum value inside array or use a custom iterator to define how items
512 should be compared.
513
514 See: [`min()`](#min)
515
516 ```js
517 max([10, 2, 7]); // 10
518 max(['foo', 'lorem', 'amet'], function(val){
519     return val.length;
520 }); // 'lorem'
521 ```
522
523 It also supports a shorthand notation:
524
525 ```js
526 max(['foo', 'lorem', 'amet'], 'length'); // "lorem"
527 ```
528
529
530
531 ## min(arr, [iterator], [thisObj]):*
532
533 Returns minimum value inside array or use a custom iterator to define how items
534 should be compared.
535
536 See: [`max()`](#max)
537
538 ```js
539 min([10, 2, 7]); // 2
540 min(['foo', 'lorem', 'amet'], function(val){
541     return val.length;
542 }); // 'foo'
543 ```
544
545 It also supports a shorthand notation:
546
547 ```js
548 min(['foo', 'lorem', 'amet'], 'length'); // "foo"
549 ```
550
551
552
553 ## pick(arr, [nItems]):*
554
555 Gets random item(s) and removes it from the original array.
556
557 If `nItems` is specified it will return a new Array contained the *picked*
558 items otherwise it returns a single item.
559
560 See: [`random/choice()`](./random.html#choice)
561
562 ### Example:
563
564 ```js
565 var arr = [1, 2, 3, 4, 5, 6];
566 var item1 = pick(arr); // 4
567 var item2 = pick(arr); // 1
568 var items = pick(arr, 2); // [5, 2]
569 console.log(arr); // [3, 6]
570 ```
571
572
573
574 ## pluck(arr, propName):Array
575
576 Extract a list of property values.
577
578 See: [`function/prop()`](function.html#prop)
579
580 ```js
581 var users = [{name : 'John', age: 21}, {name: 'Jane', age : 27}];
582 var names = pluck(users, 'name'); // ["John", "Jane"]
583 var ages = pluck(users, 'age'); // [21, 27]
584 ```
585
586
587
588 ## range([start], stop[, step]):Array
589
590 Creates a new Array with all the values inside the range. Works similarly to
591 Python#range or PHP#range.
592
593 ### Arguments
594
595  1. `[start]` (Number) : Range start. Default is `0`.
596  2. `stop` (Number) : Range limit.
597  3. `[step]` (Number) : Step size. Default is `1`.
598
599 ### Example
600
601 ```js
602 range(5);         // [0, 1, 2, 3, 4, 5]
603 range(0, 5);      // [0, 1, 2, 3, 4, 5]
604 range(0, 5, 2);   // [0, 2, 4]
605 range(20, 40, 5); // [20, 25, 30, 35, 40]
606 ```
607
608
609
610 ## reduce(arr, fn):*
611
612 Crossbrowser `Array.reduce()`.
613
614 Apply a function against an accumulator and each value of the array (from
615 left-to-right) as to reduce it to a single value.
616
617 It differs from ES5 since it will also loop over sparse items in the array to
618 normalize the behavior across browsers (avoid inconsistencies).
619
620 more info at [MDN Array#reduce](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce)
621
622
623
624 ## reduceRight(arr, fn):*
625
626 Crossbrowser `Array.reduceRight()`.
627
628 Apply a function simultaneously against two values of the array (from
629 right-to-left) as to reduce it to a single value.
630
631 It differs from ES5 since it will also loop over sparse items in the array to
632 normalize the behavior across browsers (avoid inconsistencies).
633
634 more info at [MDN Array#reduceRight](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduceRight)
635
636
637
638 ## reject(arr, fn, thisObj):Array
639
640 Creates a new array with all the elements that do **not** pass the truth test.
641 Opposite of [`filter()`](#filter).
642
643 See [`filter()`](#filter)
644
645 ### Example
646
647 ```js
648 var numbers = [1, 2, 3, 4, 5, 6];
649 reject(numbers, function(x) { return (x % 2) !== 0; }); // [2, 4, 6]
650 ```
651
652 It also supports a shorthand syntax:
653
654 ```js
655 var users = [
656     {name:'john', surname:'connor', beard:false},
657     {name:'john', surname:'doe', beard:true},
658     {name:'jane', surname:'doe', beard:false}
659 ];
660 // reject items that matches all properties/values pairs
661 reject(arr, {name:'john'});
662 // > [{name:'jane', surnname:'doe', beard:false}]
663 // reject items where 'beard' is a truthy value
664 filter(arr, 'beard');
665 // > [{name:'john', surnname:'connor', beard:false},
666 //    {name:'jane', surname:'doe', beard:false}]
667 ```
668
669
670
671 ## remove(arr, item):void
672
673 Remove a single item from the array.
674
675 IMPORTANT: it won't remove duplicates, just a single item.
676
677 ### Example
678
679 ```js
680 var foo = [1, 2, 3, 4];
681 remove(foo, 2);
682 console.log(foo); // [1, 3, 4]
683 ```
684
685
686
687 ## removeAll(arr, item):void
688
689 Remove all instances of an item from the array.
690
691 ### Example
692
693 ```js
694 var foo = [1, 2, 3, 4, 2, 2];
695 removeAll(foo, 2);
696 console.log(foo); // [1, 3, 4];
697 ```
698
699
700
701 ## shuffle(arr):Array
702
703 Returns a new Array with items randomly sorted (shuffled). Similar to Ruby Array#shuffle.
704
705 ### Example
706
707 ```js
708 var arr = ['a', 'b', 'c', 'd', 'e'];
709 shuffle(arr); // ['b', 'd', 'e', 'c', 'a']
710 ```
711
712
713
714 ## slice(arr, [start], [end]):Array
715
716 Returns a new array containing the items from `arr` from the start index to the
717 end index.
718
719 If `start` is omitted, it will start at `0`. If `end` is omitted, it will used
720 the last index of the array.  If `start` or `end` is negative, it is used as an
721 offset from the end of the array.
722
723 It will also convert array-like objects to arrays.
724
725 ### Example
726
727 ```js
728 slice([1, 2, 3, 4], 1, 2); // [2, 3]
729 slice([1, 2, 3], 1); // [2, 3]
730 slice([1, 2, 3]); // [1, 2, 3]
731 slice({ length: 2, 0: 'a', 1: 'b' }); // ['a', 'b']
732 slice([1, 2, 3], 0, -1); // [1, 2]
733 slice([1, 2, 3], -2); // [2, 3]
734 ```
735
736
737
738 ## some(arr, callback, [thisObj]):Array
739
740 Crossbrowser `Array.some()`.
741
742 Tests whether some element in the array passes the test implemented by the provided function.
743
744 It differs from ES5 since it will also loop over sparse items in the array to
745 normalize the behavior across browsers (avoid inconsistencies).
746
747 ```js
748 var items = [1, 'foo', 'bar'];
749 some(items, isString);   // true
750 some(items, isFunction); // false
751 ```
752
753 more info at [MDN Array#some](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some)
754
755 It also supports a shorthand syntax:
756
757 ```js
758 var items = [{id:1, active:true}, {id:3, active:false}, {id:8, active:false}];
759 // at least one item with `id === 8`
760 some(items, {id:8}); // true
761 // `active` is truthy on at least one item
762 some(items, 'active'); // true
763 ```
764
765 see also: [`object/matches`](object.html#matches)
766
767
768
769 ## sort(arr, [compareFn]):Array
770
771 Returns a sorted Array using the [Merge Sort](http://en.wikipedia.org/wiki/Merge_sort) algorithm (stable sort).
772
773 The `Array.prototype.sort` browser implementations differ since the sorting algorithm isn't described in the ES spec - [in V8 it isn't stable](http://code.google.com/p/v8/issues/detail?id=90) and [on Firefox it is stable](https://bugzilla.mozilla.org/show_bug.cgi?id=224128) - so this function doesn't use the browser native implementation and is recommended in cases where a stable sort is required (items should preserve same order if already sorted).
774
775 **Important:** It does logical comparisson by default (greater/less than) and
776 not a string comparisson like the native `Array#sort`.
777
778 ### compareFn
779
780 If `compareFn` is supplied elements are sorted based on the value returned by
781 the `compareFn`.
782
783  - If `compareFn(a, b)` is less than `0`, sort `a` to a lower index than `b`.
784  - If `compareFn(a, b)` returns `0`, leave `a` and `b` unchanged with respect
785    to each other, but sorted with respect to all different elements.
786  - If `compareFn(a, b)` is greater than `0`, sort `b` to a lower index than
787    `a`.
788
789 See: [`sortBy`](#sortBy)
790
791 ### Example
792
793 ```js
794 sort([187, 23, 47, 987, 12, 59, 0]); // [0, 12, 23, 47, 59, 187, 987]
795 sort(['a', 'z', 'c', 'beta', 'b']); // ['a', 'b', 'beta', 'c', 'z']
796
797 // ['sit', 'amet', 'lorem', 'ipsum']
798 sort(['lorem', 'ipsum', 'sit', 'amet'], function(a, b){
799     // sort by length, items with same length
800     // will keep the relative order (stable)
801     return a.length - b.length;
802 });
803
804 // [4, 3, 2, 1]
805 sort([2, 3, 1, 4], function(a, b){
806     // reverse sort
807     return b - a;
808 });
809 ```
810
811
812
813 ## sortBy(arr, callback, [context]):Array
814
815 Returns an array sorted by the result of the callback.
816
817 The callback is called for each item that is to be sorted, and the
818 results of the callback are used to sort the array. The callback
819 is called with the item as the first parameter, optionally with
820 the provided context.
821
822 It also supports a shorthand notation which can be used to sort by a property
823 name.
824
825 See: [`sort`](#sort)
826
827 ```js
828 // Returns [{ a: 1 }, { a: 2 }, { a: 3 }]
829 sortBy([{ a: 1 }, { a: 3 }, { a: 2 }],
830     function(item) { return item.a; });
831
832 // Same as above, using shorthand notation
833 sortBy([{ a: 1 }, { a: 3 }, { a: 2 }], 'a');
834 ```
835
836
837
838 ## split(arr, [segments]):Array
839
840 Splits an array into a fixed number of segments.
841
842 The number of segments is specified by `segments` and defaults to 2. If the
843 array cannot be evenly split, the first segments will contain the extra items.
844 If `arr` is empty, an empty array is returned. If `arr.length` is less than
845 `segments`, then the resulting array will have `arr.length` number of
846 single-element arrays.
847
848 ### Example
849 ```js
850 split([1, 2, 3, 4, 5], 3) // [ [1, 2], [3, 4], [5] ]
851 split([1, 2, 3, 4, 5]) // [ [1, 2, 3], [4, 5] ]
852 split([]) // []
853 split([1, 2], 3) // [ [1], [2] ]
854 ```
855
856
857
858 ## take(times, callback, [thisObj]):Array
859
860 Builds a new array based on the returned values from the given `callback`.
861
862 ```js
863 take(4, function(i, total) {
864     return i / total;
865 });
866 // > [0, 0.25, 0.5, 0.75]
867 ```
868
869 see: [function/times](../function.html#times)
870
871
872
873 ## toLookup(arr, key):Object
874
875 Create an object that indexes the items in the array by a key. If `key` is a function, the key for each value in the resulting object will be the result of calling the function with the value as an argument. Otherwise `key` specifies the property on each value to use as the key.
876
877 ### Example
878
879 ```js
880 var foo = [{ name: 'a', thing: 1 }, { name: 'b', thing: 2 }];
881 // { a: { name: 'a', thing: 1 }, b: { name: 'b', thing: 2 } }
882 toLookup(foo, 'name');
883 // same as above
884 toLookup(foo, function (value) { return value.name; });
885 ```
886
887
888
889 ## union(...arrs):Array
890
891 Concat multiple arrays removing duplicates.
892
893 ```js
894 var a = ['a', 'b'],
895     b = ['c', 'a'],
896     c = [1, 'b', 2, 3, 'a'];
897
898 //note that unique remove from begin to end
899 union(a, b, c); // ['c', 1, 'b', 2, 3, 'a']
900 ```
901
902
903
904 ## unique(arr, [compare]):Array
905
906 Return a new Array of unique items.
907
908 **IMPORTANT:** duplicates are removed starting from begining of array.
909
910 ```js
911 var arr = [1, 2, 3, 4, 2, 2, 4];
912 var foo = unique(arr);
913 console.log(foo);
914 // > [1, 3, 2, 4];
915
916 // you also have the option to set a custom compare function
917 var users = [{name: 'john'}, {name: 'paul'}, {name: 'john'}];
918 var uniqueNames = unique(arr, function(a, b){
919     return a.name === b.name;
920 });
921 console.log(uniqueNames);
922 // > [{name: 'paul'}, {name: 'john'}]
923 ```
924
925
926
927 ## xor(arr1, arr2):Array
928
929 Exclusive OR. Returns items that are present in a single array.
930
931 Works like [Python set#symmetric_difference](http://docs.python.org/library/stdtypes.html#set.symmetric_difference) renamed for brevity.
932
933 It will remove duplicates.
934
935 See: [`difference()`](#difference), [`intersection()`](#intersection)
936
937 ```js
938 var a = ['a', 'b', 1];
939 var b = ['c', 1];
940 xor(a, b); // ['a', 'b', 'c']
941 ```
942
943
944
945 ## zip(...arrs):Array
946
947 Groups the elements of each array at their corresponding indexes.
948
949 Useful for separate data sources that are coordinated through matching array
950 indexes. For a matrix of nested arrays, `zip.apply(...)` can transpose the
951 matrix in a similar fashion.
952
953 ```js
954 // [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]]
955 zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
956 ```
957
958
959
960
961 -------------------------------------------------------------------------------
962
963 For more usage examples check specs inside `/tests` folder. Unit tests are the
964 best documentation you can get...
965