Defined base/array.js

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]

avg Static Function Public


Defined base/array.js

Averages an array of numbers.

Example
comb.array.avg([1,2,3]); //2
        
Arguments Returns Throws Source
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;
   }
}
    

cartesian Static Function Public


Defined base/array.js

Find the cartesian product of two arrays

Example
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]
      ]
        
Arguments Source
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;
}
    

compact Static Function Public


Defined base/array.js

Compacts an array removing null or undefined objects from the array.

Example
var x;
comb.array.compact([1,null,null,x,2]) => [1,2]
comb.array.compact([1,2]) => [1,2]
        
Arguments Source
function (arr){
   var ret = [];
   if (isArray(arr) && arr.length) {
       ret = filter(arr, function (item) {
           return !misc.isUndefinedOrNull(item);
       });
   }
   return ret;
}
    

difference Static Function Public


Defined base/array.js

Finds the difference of the two arrays.

Example
comb.array.difference([1,2,3], [2,3]); //[1]
comb.array.difference(["a","b",3], [3]); //["a","b"]
        
Arguments Returns Source
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 Static Function Public


Defined base/array.js

Flatten multiple arrays into a single array

Example
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"]
        
Arguments Source
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);
   }, []);
}
    

intersect Static Function Public


Defined base/array.js

Finds the intersection of arrays NOTE : this function accepts an arbitrary number of arrays

Example
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]
        
Arguments Source
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);
}
    

invoke Static Function Public


Defined base/array.js

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.


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];

Arguments Returns Source
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);
   });
}
    

max Static Function Public


Defined base/array.js

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.

Example
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}
        
Arguments Returns Source
function (arr,cmp){
   return _sort(arr, cmp)[arr.length - 1];
}
    

min Static Function Public


Defined base/array.js

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.

Example
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}
        
Arguments Returns Source
function (arr,cmp){
   return _sort(arr, cmp)[0];
}
    

multiply Static Function Public


Defined base/array.js

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.

Arguments Returns Source
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;
}
    

partition Static Function Public


Defined base/array.js

Paritition an array.

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]]

Arguments Returns Source
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;
}
    

permutations Static Function Public


Defined base/array.js

Finds all permutations of an array

Example
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) => []
        
Arguments Source
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;
}
    

pluck Static Function Public


Defined base/array.js

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.

Example
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]
        
Arguments Returns Source
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;
}
    

powerSet Static Function Public


Defined base/array.js

Finds the powerset of an array

Example
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 ]
      ]
        
Arguments Source
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;
}
    

removeDuplicates Static Function Public


Defined base/array.js

Removes duplicates from an array

Example
comb.array.removeDuplicates([1,1,1]) => [1]
comb.array.removeDuplicates([1,2,3,2]) => [1,2,3]
        
Arguments Source
function (arr){
   if (isArray(arr)) {
       return reduce(arr, function (a, b) {
           if (indexOf(a, b) === -1) {
               return a.concat(b);
           } else {
               return a;
           }
       }, []);
   }
}
    

rotate Static Function Public


Defined base/array.js

Rotates an array the number of specified positions

Example
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"]);
        
Arguments Source
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;
   }
}
    

sort Static Function Public


Defined base/array.js

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!

Example
comb.array.sort([{a : 1}, {a : 2}, {a : -2}], "a"); //[{a : -2}, {a : 1}, {a : 2}];
        
Arguments Returns Source
function (arr,cmp){
   return _sort(arr, cmp);
}
    

sum Static Function Public


Defined base/array.js

Sums all items in an array

Example
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]";
        
Arguments Source
function (array){
   array = array || [];
   if (array.length) {
       return reduce(array, function (a, b) {
           return a + b;
       });
   } else {
       return 0;
   }
}
    

toArray Static Function Public


Defined base/array.js

converts anything to an array

Example
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"]];
        
Arguments Source
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;
}
    

transpose Static Function Public


Defined base/array.js

Transposes an array of arrays

Example
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]])
        
Arguments Source
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 Static Function Public


Defined base/array.js

Union a variable number of arrays together

Example
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"]
        
Arguments Source
function (){
   var ret = [];
   var arrs = argsToArray(arguments);
   if (arrs.length > 1) {
       ret = removeDuplicates(reduce(arrs, function (a, b) {
           return a.concat(b);
       }, []));
   }
   return ret;
}
    

unique Static Function Public


Defined base/array.js

See comb.array.removeDuplicates

Arguments Source
function (arr){
   return removeDuplicates(arr);
}
    

valuesAt Static Function Public


Defined base/array.js

Retrieves values at specified indexes in the array

Example
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"];
        
Arguments Source
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;
}
    

zip Static Function Public


Defined base/array.js

Zips to arrays together

Example
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]]
        
Arguments Source
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;
}
    

License

MIT https://github.com/C2FO/comb/raw/master/LICENSE

Meta