Utilities for working with arrays.
The comb.array
namespace can be used to decorate arrays with additional chainable functionality.
var arr = comb.array([1,3,2,5,4,6]);
console.log(arr.sum()) //21
console.log(arr.sort()) //[1,2,3,4,5,6]
console.log(arr.min()) //[1]
console.log(arr.max()) [6]
Averages an array of numbers.
ExampleArguments
- comb.array.avg([1,2,3]); //2
Number[]
: Number
the average of all the numbers in the array.
Error
if the array is not all numbers.
- function (arr){
- arr = arr || [];
- if (arr.length) {
- var total = sum(arr);
- if (number.isNumber(total)) {
- return total / arr.length;
- } else {
- throw new Error("Cannot average an array of non numbers.");
- }
- } else {
- return 0;
- }
- }
Find the cartesian product of two arrays
ExampleArguments
- comb.array.cartesian([1,2], [2,3]) => [
- [1,2],
- [1,3],
- [2,2],
- [2,3]
- ]
- comb.array.cartesian([1,2], [2,3,4]) => [
- [1,2],
- [1,3],
- [1,4] ,
- [2,2],
- [2,3],
- [2,4]
- ]
- comb.array.cartesian([1,2,3], [2,3,4]) => [
- [1,2],
- [1,3],
- [1,4] ,
- [2,2],
- [2,3],
- [2,4] ,
- [3,2],
- [3,3],
- [3,4]
- ]
- function (a,b){
- var ret = [];
- if (isArray(a) && isArray(b) && a.length && b.length) {
- ret = cross(a[0], b).concat(cartesian(a.slice(1), b));
- }
- return ret;
- }
Compacts an array removing null or undefined objects from the array.
ExampleArguments
- var x;
- comb.array.compact([1,null,null,x,2]) => [1,2]
- comb.array.compact([1,2]) => [1,2]
- function (arr){
- var ret = [];
- if (isArray(arr) && arr.length) {
- ret = filter(arr, function (item) {
- return !misc.isUndefinedOrNull(item);
- });
- }
- return ret;
- }
Finds the difference of the two arrays.
ExampleArguments
- comb.array.difference([1,2,3], [2,3]); //[1]
- comb.array.difference(["a","b",3], [3]); //["a","b"]
the array we are subtracting from
the array we are subtracting from arr1
*
the difference of the arrays.
- function (arr1,arr2){
- var ret = arr1, args = flatten(argsToArray(arguments, 1));
- if (isArray(arr1)) {
- ret = filter(arr1, function (a) {
- return indexOf(args, a) === -1;
- });
- }
- return ret;
- }
Flatten multiple arrays into a single array
ExampleArguments
- comb.array.flatten([1,2], [2,3], [3,4]) => [1,2,2,3,3,4]
- comb.array.flatten([1,"A"], [2,"B"], [3,"C"]) => [1,"A",2,"B",3,"C"]
- function (arr){
- var set;
- var args = argsToArray(arguments);
- if (args.length > 1) {
- //assume we are intersections all the lists in the array
- set = args;
- } else {
- set = toArray(arr);
- }
- return reduce(set, function (a, b) {
- return a.concat(b);
- }, []);
- }
Finds the intersection of arrays NOTE : this function accepts an arbitrary number of arrays
ExampleArguments
- comb.array.intersect([1,2], [2,3], [2,3,5]) => [2]
- comb.array.intersect([1,2,3], [2,3,4,5], [2,3,5]) => [2,3]
- comb.array.intersect([1,2,3,4], [2,3,4,5], [2,3,4,5]) => [2,3,4]
- comb.array.intersect([1,2,3,4,5], [1,2,3,4,5], [1,2,3]) => [1,2,3]
- comb.array.intersect([[1,2,3,4,5],[1,2,3,4,5],[1,2,3]]) => [1,2,3]
- function (a,b){
- var collect = [], set;
- var args = argsToArray(arguments);
- if (args.length > 1) {
- //assume we are intersections all the lists in the array
- set = args;
- } else {
- set = args[0];
- }
- if (isArray(set)) {
- var x = set.shift();
- collect = reduce(set, function (a, b) {
- return intersection(a, b);
- }, x);
- }
- return removeDuplicates(collect);
- }
Invokes the method specified in the scope of each item in the array. If you supply addional arguments they will be applied to the function.
Arguments
function person(name, age){
return {
getName : function(){
return name;
},
setName : function(newName){
name = newName;
},
getOlder : function(){
age++;
return this;
},
getAge : function(){
return age;
}
};
}
var arr = [person("Bob", 40), person("Alice", 35), person("Fred", 50), person("Johnny", 56)];
console.log(comb.array.invoke(arr, "getName")); //["Bob", "Alice", "Fred", "Johnny"]
console.log(comb.array(arr).invoke("getOlder").invoke("getAge")); //[41, 36, 51, 57];
the array to iterate and invoke the functions on
the function to invoke, if it is a string then the function will be looked up on the each item in the array and invoked
null
] : variable number of arguments to apply to the function
Array
the return values of the functions invoked.
- function (arr,func,args){
- args = argsToArray(arguments, 2);
- return map(arr, function (item) {
- var exec = isString(func) ? item[func] : func;
- return exec.apply(item, args);
- });
- }
Finds that max value of an array. If a second argument is provided and it is a function it will be used as a comparator function. If the second argument is a string then it will be used as a property look up on each item.
ExampleArguments
- comb.array.max([{a : 1}, {a : 2}, {a : -2}], "a"); //{a : 2}
- comb.array.max([{a : 1}, {a : 2}, {a : -2}], function(a,b){
- return a.a - b.a
- }); //{a : 2}
the array to find the max value on
the property to sort on. Or a function used to compare.
*
the maximum value of the array based on the provided cmp.
- function (arr,cmp){
- return _sort(arr, cmp)[arr.length - 1];
- }
Finds that min value of an array. If a second argument is provided and it is a function it will be used as a comparator function. If the second argument is a string then it will be used as a property look up on each item.
ExampleArguments
- comb.array.min([{a : 1}, {a : 2}, {a : -2}], "a"); //{a : -2}
- comb.array.min([{a : 1}, {a : 2}, {a : -2}], function(a,b){
- return a.a - b.a
- }); //{a : -2}
the array to find the min value on
the property to sort on. Or a function used to compare.
*
- function (arr,cmp){
- return _sort(arr, cmp)[0];
- }
Creates a new array that is the result of the array concated the number of times. If times is not specified or it equals 0 then it defaults to 1.
Argumentsthe array to multiply.
1
] : the number of times to multiple the array.
Array
a new array that is the result of the array multiplied the number of times specified.
- function (arr,times){
- times = number.isNumber(times) ? times : 1;
- if (!times) {
- //make sure times is greater than zero if it is zero then dont multiply it
- times = 1;
- }
- arr = toArray(arr || []);
- var ret = [], i = 0;
- while (++i <= times) {
- ret = ret.concat(arr);
- }
- return ret;
- }
Paritition an array.
Arguments
var arr = [1,2,3,4,5];
comb.array.partition(arr, 1); //[[1], [2], [3], [4], [5]]
comb.array.partition(arr, 2); //[[1,2], [3,4], [5]]
comb.array.partition(arr, 3); //[[1,2,3], [4,5]]
comb.array.partition(arr); //[[1, 2, 3, 4, 5]]
comb.array.partition(arr, 0); //[[1, 2, 3, 4, 5]]
Array
- function (array,partitionSize){
- partitionSize = partitionSize || array.length;
- var ret = [];
- for (var i = 0, l = array.length; i < l; i += partitionSize) {
- ret.push(array.slice(i, i + partitionSize));
- }
- return ret;
- }
Finds all permutations of an array
ExampleArguments
- var arr = [1,2,3];
- comb.array.permutations(arr) => [[ 1, 2, 3 ],[ 1, 3, 2 ],[ 2, 3, 1 ],
- [ 2, 1, 3 ],[ 3, 1, 2 ],[ 3, 2, 1 ]]
- comb.array.permutations(arr, 2) => [[ 1, 2],[ 1, 3],[ 2, 3],[ 2, 1],[ 3, 1],[ 3, 2]]
- comb.array.permutations(arr, 1) => [[1],[2],[3]]
- comb.array.permutations(arr, 0) => [[]]
- comb.array.permutations(arr, 4) => []
the array to permute.
the number of elements to permute.
- function (arr,length){
- var ret = [];
- if (isArray(arr)) {
- var copy = arr.slice(0);
- if (typeof length !== "number") {
- length = arr.length;
- }
- if (!length) {
- ret = [
- []
- ];
- } else if (length <= arr.length) {
- ret = reduce(arr, function (a, b, i) {
- var ret;
- if (length > 1) {
- ret = permute(b, rotate(copy, i).slice(1), length);
- } else {
- ret = [
- [b]
- ];
- }
- return a.concat(ret);
- }, []);
- }
- }
- return ret;
- }
Plucks values from an array. Effectevily the same as using a array.map implementation. However the porperty specified supports a "dot" notation to access nested properties.
ExampleArguments
- var arr = [
- {name:{first:"Fred", last:"Jones"}, age:50, roles:["a", "b", "c"]},
- {name:{first:"Bob", last:"Yukon"}, age:40, roles:["b", "c"]},
- {name:{first:"Alice", last:"Palace"}, age:35, roles:["c"]},
- {name:{first:"Johnny", last:"P."}, age:56, roles:[]}
- ];
- console.log(comb.array.pluck(arr, "name.first")); //["Fred", "Bob", "Alice", "Johnny"]
- console.log(comb.array.pluck(arr, "age")); //[50, 40, 35, 56]
- console.log(comb.array.pluck(arr, "roles.length")); //[3, 2, 1, 0]
- console.log(comb.array.pluck(arr, "roles.0")); //["a", "b", "c", undefined]
the array to pluck values from
the property to retrieve from each item in the array
Array
an array containing the plucked properties.
- function (arr,prop){
- prop = prop.split(".");
- var result = arr.slice(0);
- forEach(prop, function (prop) {
- var exec = prop.match(/(\w+)\(\)$/);
- result = map(result, function (item) {
- return exec ? item[exec[1]]() : item[prop];
- });
- });
- return result;
- }
Finds the powerset of an array
ExampleArguments
- comb.array.powerSet([1,2]) => [
- [],
- [ 1 ],
- [ 2 ],
- [ 1, 2 ]
- ]
- comb.array.powerSet([1,2,3]) => [
- [],
- [ 1 ],
- [ 2 ],
- [ 1, 2 ],
- [ 3 ],
- [ 1, 3 ],
- [ 2, 3 ],
- [ 1, 2, 3 ]
- ]
- comb.array.powerSet([1,2,3,4]) => [
- [],
- [ 1 ],
- [ 2 ],
- [ 1, 2 ],
- [ 3 ],
- [ 1, 3 ],
- [ 2, 3 ],
- [ 1, 2, 3 ],
- [ 4 ],
- [ 1, 4 ],
- [ 2, 4 ],
- [ 1, 2, 4 ],
- [ 3, 4 ],
- [ 1, 3, 4 ],
- [ 2, 3, 4 ],
- [ 1, 2, 3, 4 ]
- ]
the array to find the powerset of
- function (arr){
- var ret = [];
- if (isArray(arr) && arr.length) {
- ret = reduce(arr, function (a, b) {
- var ret = map(a, function (c) {
- return c.concat(b);
- });
- return a.concat(ret);
- }, [
- []
- ]);
- }
- return ret;
- }
Removes duplicates from an array
ExampleArguments
- comb.array.removeDuplicates([1,1,1]) => [1]
- comb.array.removeDuplicates([1,2,3,2]) => [1,2,3]
Aray
: the array of elements to remove duplicates from
- function (arr){
- if (isArray(arr)) {
- return reduce(arr, function (a, b) {
- if (indexOf(a, b) === -1) {
- return a.concat(b);
- } else {
- return a;
- }
- }, []);
- }
- }
Rotates an array the number of specified positions
ExampleArguments
- var arr = ["a", "b", "c", "d"];
- comb.array.rotate(arr) => ["b", "c", "d", "a"]
- comb.array.rotate(arr, 2) => ["c", "d", "a", "b"]);
- comb.array.rotate(arr, 3) => ["d", "a", "b", "c"]);
- comb.array.rotate(arr, 4) => ["a", "b", "c", "d"]);
- comb.array.rotate(arr, -1) => ["d", "a", "b", "c"]);
- comb.array.rotate(arr, -2) => ["c", "d", "a", "b"]);
- comb.array.rotate(arr, -3) => ["b", "c", "d", "a"]);
- comb.array.rotate(arr, -4) => ["a", "b", "c", "d"]);
the number of times to rotate the array
Array
: the array of elements to remove duplicates from
- function (arr,numberOfTimes){
- var ret = arr.slice();
- if (typeof numberOfTimes !== "number") {
- numberOfTimes = 1;
- }
- if (numberOfTimes && isArray(arr)) {
- if (numberOfTimes > 0) {
- ret.push(ret.shift());
- numberOfTimes--;
- } else {
- ret.unshift(ret.pop());
- numberOfTimes++;
- }
- return rotate(ret, numberOfTimes);
- } else {
- return ret;
- }
- }
Allows the sorting of an array based on a property name instead. This can also act as a sort that does not change the original array.
NOTE: this does not change the original array!
ExampleArguments
- comb.array.sort([{a : 1}, {a : 2}, {a : -2}], "a"); //[{a : -2}, {a : 1}, {a : 2}];
the array to sort
the property to sort on. Or a function used to compare.
Array
a copy of the original array that is sorted.
- function (arr,cmp){
- return _sort(arr, cmp);
- }
Sums all items in an array
ExampleArguments
- comb.array.sum([1,2,3]) => 6
- comb.array.sum(["A","B","C"]) => "ABC";
- var d1 = new Date(1999), d2 = new Date(2000), d3 = new Date(3000);
- comb.array.sum([d1,d2,d3]) => "Wed Dec 31 1969 18:00:01 GMT-0600 (CST)"
- + "Wed Dec 31 1969" 18:00:02 GMT-0600 (CST)"
- + "Wed Dec 31 1969 18:00:03 GMT-0600 (CST)"
- comb.array.sum([{},{},{}]) => "[object Object][object Object][object Object]";
the array of numbers to sum
- function (array){
- array = array || [];
- if (array.length) {
- return reduce(array, function (a, b) {
- return a + b;
- });
- } else {
- return 0;
- }
- }
converts anything to an array
ExampleArguments
- comb.array.toArray({a : "b", b : "c"}) => [["a","b"], ["b","c"]];
- comb.array.toArray("a") => ["a"]
- comb.array.toArray(["a"]) => ["a"];
- comb.array.toArray() => [];
- comb.array.toArray("a", {a : "b"}) => ["a", ["a", "b"]];
- function (o){
- var ret = [];
- if (o != null) {
- var args = argsToArray(arguments);
- if (args.length === 1) {
- if (isArray(o)) {
- ret = o;
- } else if (obj.isHash(o)) {
- for (var i in o) {
- if (o.hasOwnProperty(i)) {
- ret.push([i, o[i]]);
- }
- }
- } else {
- ret.push(o);
- }
- } else {
- forEach(args, function (a) {
- ret = ret.concat(toArray(a));
- });
- }
- }
- return ret;
- }
Transposes an array of arrays
ExampleArguments
- comb.array.transpose([[1,2,3], [4,5,6]]) => [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
- comb.array.transpose([[1,2], [3,4], [5,6]]) => [ [ 1, 3, 5 ], [ 2, 4, 6 ] ]
- comb.array.transpose([[1], [3,4], [5,6]]) => [[1]])
arr Array of arrays
- function (arr){
- var ret = [];
- if (isArray(arr) && arr.length) {
- var last;
- forEach(arr, function (a) {
- if (isArray(a) && (!last || a.length === last.length)) {
- forEach(a, function (b, i) {
- if (!ret[i]) {
- ret[i] = [];
- }
- ret[i].push(b);
- });
- last = a;
- }
- });
- }
- return ret;
- }
Union a variable number of arrays together
ExampleArguments
- comb.array.union(['a','b','c'], ['b','c', 'd']) => ["a", "b", "c", "d"]
- comb.array.union(["a"], ["b"], ["c"], ["d"], ["c"]) => ["a", "b", "c", "d"]
variable number of arrays to union
- function (){
- var ret = [];
- var arrs = argsToArray(arguments);
- if (arrs.length > 1) {
- ret = removeDuplicates(reduce(arrs, function (a, b) {
- return a.concat(b);
- }, []));
- }
- return ret;
- }
See comb.array.removeDuplicates
Arguments
- function (arr){
- return removeDuplicates(arr);
- }
Retrieves values at specified indexes in the array
ExampleArguments
- var arr =["a", "b", "c", "d"]
- comb.array.valuesAt(arr, 1,2,3) => ["b", "c", "d"];
- comb.array.valuesAt(arr, 1,2,3, 4) => ["b", "c", "d", null];
- comb.array.valuesAt(arr, 0,3) => ["a", "d"];
the array to retrieve values from
variable number of indexes to retrieve
- function (arr,indexes){
- var ret = [];
- indexes = argsToArray(arguments);
- arr = indexes.shift();
- var l = arr.length;
- if (isArray(arr) && indexes.length) {
- for (var i = 0; i < indexes.length; i++) {
- ret.push(arr[indexes[i]] || null);
- }
- }
- return ret;
- }
Zips to arrays together
ExampleArguments
- var a = [ 4, 5, 6 ], b = [ 7, 8, 9 ]
- comb.array.zip([1], [2], [3]) => [[ 1, 2, 3 ]]);
- comb.array.zip([1,2], [2], [3]) => [[ 1, 2, 3 ],[2, null, null]]
- comb.array.zip([1,2,3], a, b) => [[1, 4, 7],[2, 5, 8],[3, 6, 9]]
- comb.array.zip([1,2], a, b) => [[1, 4, 7],[2, 5, 8]]
- comb.array.zip(a, [1,2], [8]) => [[4,1,8],[5,2,null],[6,null,null]]
variable number of arrays to zip together
- function (){
- var ret = [];
- var arrs = argsToArray(arguments);
- if (arrs.length > 1) {
- var arr1 = arrs.shift();
- if (isArray(arr1)) {
- ret = reduce(arr1, function (a, b, i) {
- var curr = [b];
- for (var j = 0; j < arrs.length; j++) {
- var currArr = arrs[j];
- if (isArray(currArr) && !misc.isUndefined(currArr[i])) {
- curr.push(currArr[i]);
- } else {
- curr.push(null);
- }
- }
- a.push(curr);
- return a;
- }, []);
- }
- }
- return ret;
- }
MIT https://github.com/C2FO/comb/raw/master/LICENSE
git clone git://github.com/C2FO/comb.git