Skip to content

Instantly share code, notes, and snippets.

@jiggzson
Created November 10, 2014 00:00
Show Gist options
  • Save jiggzson/3be6d2bf71207d06e44d to your computer and use it in GitHub Desktop.
Save jiggzson/3be6d2bf71207d06e44d to your computer and use it in GitHub Desktop.
/**
* This function searches an array and its sub-arrays. A condition function can be used
* to limit the results
* @param {Array} arr
* @param {Function} condfn A function with extra conditions
* @param {String} prop A hashable property to identify the object when found
* @param {Object} c A collector object defined by the function
* @returns {Object} An object containing the found objects
*/
function countFrequency(arr, condfn, prop, c) {
c = c || {
items: {},//items to be returned
add: function(item, cond) {
var hash = prop !== undefined ? item[prop] : item;
if(cond) { //if the condition test true
//if no item was found then add it
if(!this.items[hash]) this.items[hash] = 1;
//otherwise increment the counter
else this.items[hash]++;
}
}
};
var l = arr.length;
for(var i=0; i<l; i++) {
var item = arr[i]; //the current item
//call the function recursively with the branch-array
if(item instanceof Array) searchArray(item, condfn, prop, c);
else {
//test to see if the object meet the criteria. If not function is
//found the set to true
var cond = condfn ? condfn.call(undefined, item) : true;
c.add(item, cond);
}
}
return c.items; //done
}
/*====================EXAMPLES =====================*/
var a = [9,8,9,[6,1,[2,9]]];
console.log(searchArray(a));
//result: { '1': 1, '2': 1, '6': 1, '8': 1, '9': 3 }
var b = [9,8,9,[6,1,[2,9]]];
console.log(searchArray(b, function(item){ return item % 3 === 0; }));
//result: { '6': 1, '9': 3 }
var c = [['frank', 'arthur'],'annie', 'bruce', 'anthon',['simone', 'andrew']];
console.log(searchArray(c, function(name){return name.charAt(0) === 'a'; }));
//result: { arthur: 1, annie: 1, anthon: 1, andrew: 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment