8 ## append(arr1, arr2):Array
10 Appends an array to the end of the other.
11 The first array will be modified and will contain the appended items.
13 See: [`union()`](#union), [`combine()`](#combine)
19 append(foo, bar); // ['a', 'b', 'b', 'd']
24 ## collect(arr, callback, [thisObj]):Array
26 Maps the items in `arr` and concatenates the resulting arrays.
31 collect([1, 2, 3], function(val) {
32 return [val, val % 2];
33 }); // [1, 1, 2, 0, 3, 1];
35 collect(['a', 'bb', ''], function(val) {
37 }); // ['a', 'b', 'b']
40 It also supports a shorthand syntax:
43 var items = [{ a: [1] }, { b: 'foo' }, { a: [2, 3] }];
44 collect(items, 'a'); // [1, 2, 3];
49 ## combine(arr1, arr2):Array
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.
55 See: [`union()`](#union), [`append()`](#append)
61 combine(foo, bar); // ['a', 'b', 'd']
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).
72 var arr = [0, 1, null, false, '', 'foo', undefined, 'bar'];
73 compact(arr); // [0, 1, false, '', 'foo', 'bar'];
78 ## contains(arr, value):Boolean
80 Checks if Array contains value. Alias to `indexOf(arr, val) !== -1`.
84 contains(arr, 2); // true
85 contains(arr, 'foo'); // false
90 ## difference(...arrs):Array
92 Return a new Array with elements that aren't present in the other Arrays
93 besides the first one.
95 Works like [Python set#difference](http://docs.python.org/library/stdtypes.html#set.difference).
97 It will remove duplicates.
99 See: [`xor()`](#xor), [`intersection()`](#intersection)
102 var a = ['a', 'b', 1];
104 difference(a, b); // ['a', 'b']
108 ## equals(a, b, [compare]):Boolean
110 Checks if both arrays are equal.
113 equals([1, 2], [1, 2]); // true
114 equals([2, 4], [1, 2]); // false
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.
121 function loose(a, b) {
124 equals(['1', 2], [1, 2], loose); // true
127 See: [object/equals](object.html#equals), [lang/deepEquals](lang.html#deepEquals)
131 ## every(arr, callback, [thisObj]):Array
133 Crossbrowser `Array.every()`.
135 Tests whether all elements in the array pass the test implemented by the provided function.
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).
141 var items = [1, 'foo', 'bar'];
142 every(items, isString); // false
143 every(items, isFunction); // false
144 every(items, function(val, key, arr){
149 more info at [MDN Array#every](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every)
151 It also supports a shorthand syntax:
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
163 ## filter(arr, callback, [thisObj]):Array
165 Crossbrowser `Array.filter()`.
167 Creates a new array with all elements that pass the callback test.
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).
173 var nums = [1, 2, 3, 4, 5, 6];
174 var oddNumbers = filter(nums, function(val, key, arr){
175 return (val % 2) !== 0;
180 more info at [MDN Array#filter](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter)
182 Filter also supports shorthand notation:
186 {name:'john', surname:'connor', beard:false},
187 {name:'john', surname:'doe', beard:true},
188 {name:'jane', surname:'doe', beard:false}
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}]
198 See [`reject()`](#reject)
202 ## find(arr, callback, [thisObj]):*
204 Loops through all the items in the Array and returns the first one that passes
205 a truth test (callback).
208 var arr = [123, {a:'b'}, 'foo', 'bar'];
209 find(arr, isString); // "foo"
210 find(arr, isNumber); // 123
211 find(arr, isObject); // {a:'b'}
214 Find also supports shorthand notation:
218 {name:'john', surname:'connor', beard:false},
219 {name:'john', surname:'doe', beard:true}
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}
227 See: [findIndex()](#findIndex), [findLast()](#findLast),
228 [findLastIndex()](#findLastIndex)
232 ## findLast(arr, callback, [thisObj]):*
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).
238 var arr = [123, {a:'b'}, 'foo', 'bar'];
239 findLast(arr, isString); // "bar"
240 findLast(arr, isNumber); // 123
241 findLast(arr, isObject); // {a:'b'}
244 `findLast` also supports shorthand notation:
248 {name:'john', surname:'connor', beard:false},
249 {name:'john', surname:'doe', beard:true}
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}
257 See: [find()](#find), [findIndex()](#findIndex),
258 [findLastIndex()](#findLastIndex)
262 ## findIndex(arr, iterator, [thisObj]):Number
264 Loops through the items in the Array and returns the index of the first one
265 that passes a truth test (callback).
267 Returns `-1` if no item was found that passes the truth test.
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
277 `findIndex` also supports shorthand notation:
281 { pet: 'dog', name: 'Sam' },
282 { pet: 'dog', name: 'Maggie' }
285 findIndex(pets, { pet: 'dog' }); // 0
286 findIndex(pets, { name: 'Maggie' }); // 1
289 See: [find()](#find), [findLastIndex()](#findLastIndex)
293 ## findLastIndex(arr, iterator, [thisObj]):Number
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).
298 Returns `-1` if no item was found that passes the truth test.
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
308 `findLastndex` also supports shorthand notation:
312 { pet: 'dog', name: 'Sam' },
313 { pet: 'dog', name: 'Maggie' }
316 findLastIndex(pets, { pet: 'dog' }); // 1
317 findLastIndex(pets, { name: 'Sam' }); // 0
320 See: [find()](#find), [findIndex()](#findIndex)
324 ## flatten(arr, [level]):Array
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.
332 flatten([1, [2], [3, [4, 5]]]);
334 flatten([1, [2], [3, [4, 5]]], 1);
335 // > [1, 2, 3, [4, 5]]
340 ## forEach(arr, callback, [thisObj]):void
342 Crossbrowser `Array.forEach()`.
344 It allows exiting the iteration early by returning `false` on the callback.
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).
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)
360 more info at [MDN Array#forEach](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach)
364 ## groupBy(arr, [categorize=identity], [thisObj]):Object
366 Groups array elements by the `key` returned from the `categorize` function.
368 It will use the [function/identity](function.html#identity) as the default
369 `categorize` function.
372 var items = ['lorem', 'ipsum', 'foo', 'bar', 'baz'];
373 groupBy(items, function(val) { return val.length });
374 // > {'3': ['foo', 'bar', 'baz'], '5': ['lorem', 'ipsum']}
379 ## indexOf(arr, item, [fromIndex]):Number
381 Crossbrowser `Array.indexOf()`.
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).
386 more info at [MDN Array#indexOf](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf)
391 ## insert(arr, ...items):Number
393 Push items into array only if they aren't contained by it. Returns the new
394 `length` of the array.
396 See: [`remove()`](#remove), [`removeAll()`](#removeAll),
397 [`contains()`](#contains)
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]
408 ## intersection(...arrs):Array
410 Return a new Array with elements common to all Arrays.
412 Similar to Python set#intersection and underscore.js intersection.
414 It will remove duplicates.
416 See: [`difference()`](#difference), [`xor()`](#xor)
419 var a = ['a', 'b', 1],
422 intersection(a, b, c); // [1]
427 ## invoke(arr, methodName[, ...args]):Array
429 Call `methodName` on each item of the array passing custom arguments if needed.
432 invoke([[3,2,1], [9,5,2]], 'sort'); // [[1,2,3], [2,5,9]]
437 ## join(arr, [separator]):String
439 Joins the strings in `arr`, inserting `separator` between each value.
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
448 join(['a', 'b', 'c']); // 'abc'
449 join(['foo', 'bar'], ', '); // 'foo, bar'
450 join([null, 'foo', '', 'bar', undefined], ':'); // 'foo:bar'
456 Returns the last element of an array without modifying the array.
460 last( [1, 2, 3, 4] ) // > 4
461 last( ['foo', 'bar'] ) // > 'bar'
465 ## lastIndexOf(arr, item, [fromIndex]):Number
467 Crossbrowser `Array.lastIndexOf()`.
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).
472 more info at [MDN Array#lastIndexOf](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf)
476 ## map(arr, callback, [thisObj]]):Array
478 Crossbrowser `Array.map()`.
480 Creates a new array with the results of calling a provided function on every
481 element in this array.
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).
486 See: [`collect()`](#collect)
489 var nums = [1,2,3,4];
490 var double = map(nums, function(val, key, arr){
496 more info at [MDN Array#map](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map)
498 It also supports a shorthand notation which can be used to achieve same result
499 as [`array/pluck`](#pluck):
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]
509 ## max(arr, [iterator], [thisObj]):*
511 Returns maximum value inside array or use a custom iterator to define how items
517 max([10, 2, 7]); // 10
518 max(['foo', 'lorem', 'amet'], function(val){
523 It also supports a shorthand notation:
526 max(['foo', 'lorem', 'amet'], 'length'); // "lorem"
531 ## min(arr, [iterator], [thisObj]):*
533 Returns minimum value inside array or use a custom iterator to define how items
539 min([10, 2, 7]); // 2
540 min(['foo', 'lorem', 'amet'], function(val){
545 It also supports a shorthand notation:
548 min(['foo', 'lorem', 'amet'], 'length'); // "foo"
553 ## pick(arr, [nItems]):*
555 Gets random item(s) and removes it from the original array.
557 If `nItems` is specified it will return a new Array contained the *picked*
558 items otherwise it returns a single item.
560 See: [`random/choice()`](./random.html#choice)
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]
574 ## pluck(arr, propName):Array
576 Extract a list of property values.
578 See: [`function/prop()`](function.html#prop)
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]
588 ## range([start], stop[, step]):Array
590 Creates a new Array with all the values inside the range. Works similarly to
591 Python#range or PHP#range.
595 1. `[start]` (Number) : Range start. Default is `0`.
596 2. `stop` (Number) : Range limit.
597 3. `[step]` (Number) : Step size. Default is `1`.
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]
612 Crossbrowser `Array.reduce()`.
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.
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).
620 more info at [MDN Array#reduce](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce)
624 ## reduceRight(arr, fn):*
626 Crossbrowser `Array.reduceRight()`.
628 Apply a function simultaneously against two values of the array (from
629 right-to-left) as to reduce it to a single value.
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).
634 more info at [MDN Array#reduceRight](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduceRight)
638 ## reject(arr, fn, thisObj):Array
640 Creates a new array with all the elements that do **not** pass the truth test.
641 Opposite of [`filter()`](#filter).
643 See [`filter()`](#filter)
648 var numbers = [1, 2, 3, 4, 5, 6];
649 reject(numbers, function(x) { return (x % 2) !== 0; }); // [2, 4, 6]
652 It also supports a shorthand syntax:
656 {name:'john', surname:'connor', beard:false},
657 {name:'john', surname:'doe', beard:true},
658 {name:'jane', surname:'doe', beard:false}
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}]
671 ## remove(arr, item):void
673 Remove a single item from the array.
675 IMPORTANT: it won't remove duplicates, just a single item.
680 var foo = [1, 2, 3, 4];
682 console.log(foo); // [1, 3, 4]
687 ## removeAll(arr, item):void
689 Remove all instances of an item from the array.
694 var foo = [1, 2, 3, 4, 2, 2];
696 console.log(foo); // [1, 3, 4];
701 ## shuffle(arr):Array
703 Returns a new Array with items randomly sorted (shuffled). Similar to Ruby Array#shuffle.
708 var arr = ['a', 'b', 'c', 'd', 'e'];
709 shuffle(arr); // ['b', 'd', 'e', 'c', 'a']
714 ## slice(arr, [start], [end]):Array
716 Returns a new array containing the items from `arr` from the start index to the
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.
723 It will also convert array-like objects to arrays.
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]
738 ## some(arr, callback, [thisObj]):Array
740 Crossbrowser `Array.some()`.
742 Tests whether some element in the array passes the test implemented by the provided function.
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).
748 var items = [1, 'foo', 'bar'];
749 some(items, isString); // true
750 some(items, isFunction); // false
753 more info at [MDN Array#some](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some)
755 It also supports a shorthand syntax:
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
765 see also: [`object/matches`](object.html#matches)
769 ## sort(arr, [compareFn]):Array
771 Returns a sorted Array using the [Merge Sort](http://en.wikipedia.org/wiki/Merge_sort) algorithm (stable sort).
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).
775 **Important:** It does logical comparisson by default (greater/less than) and
776 not a string comparisson like the native `Array#sort`.
780 If `compareFn` is supplied elements are sorted based on the value returned by
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
789 See: [`sortBy`](#sortBy)
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']
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;
805 sort([2, 3, 1, 4], function(a, b){
813 ## sortBy(arr, callback, [context]):Array
815 Returns an array sorted by the result of the callback.
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.
822 It also supports a shorthand notation which can be used to sort by a property
828 // Returns [{ a: 1 }, { a: 2 }, { a: 3 }]
829 sortBy([{ a: 1 }, { a: 3 }, { a: 2 }],
830 function(item) { return item.a; });
832 // Same as above, using shorthand notation
833 sortBy([{ a: 1 }, { a: 3 }, { a: 2 }], 'a');
838 ## split(arr, [segments]):Array
840 Splits an array into a fixed number of segments.
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.
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] ]
853 split([1, 2], 3) // [ [1], [2] ]
858 ## take(times, callback, [thisObj]):Array
860 Builds a new array based on the returned values from the given `callback`.
863 take(4, function(i, total) {
866 // > [0, 0.25, 0.5, 0.75]
869 see: [function/times](../function.html#times)
873 ## toLookup(arr, key):Object
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.
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');
884 toLookup(foo, function (value) { return value.name; });
889 ## union(...arrs):Array
891 Concat multiple arrays removing duplicates.
896 c = [1, 'b', 2, 3, 'a'];
898 //note that unique remove from begin to end
899 union(a, b, c); // ['c', 1, 'b', 2, 3, 'a']
904 ## unique(arr, [compare]):Array
906 Return a new Array of unique items.
908 **IMPORTANT:** duplicates are removed starting from begining of array.
911 var arr = [1, 2, 3, 4, 2, 2, 4];
912 var foo = unique(arr);
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;
921 console.log(uniqueNames);
922 // > [{name: 'paul'}, {name: 'john'}]
927 ## xor(arr1, arr2):Array
929 Exclusive OR. Returns items that are present in a single array.
931 Works like [Python set#symmetric_difference](http://docs.python.org/library/stdtypes.html#set.symmetric_difference) renamed for brevity.
933 It will remove duplicates.
935 See: [`difference()`](#difference), [`intersection()`](#intersection)
938 var a = ['a', 'b', 1];
940 xor(a, b); // ['a', 'b', 'c']
945 ## zip(...arrs):Array
947 Groups the elements of each array at their corresponding indexes.
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.
954 // [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]]
955 zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
961 -------------------------------------------------------------------------------
963 For more usage examples check specs inside `/tests` folder. Unit tests are the
964 best documentation you can get...