Skip to content

Instantly share code, notes, and snippets.

@sushiljainam
Last active December 27, 2016 11:06
Show Gist options
  • Save sushiljainam/812498e07266402812a7b8c5e6f9bd85 to your computer and use it in GitHub Desktop.
Save sushiljainam/812498e07266402812a7b8c5e6f9bd85 to your computer and use it in GitHub Desktop.
object as filter to filter array of objects returning array of lesser objects
Array.prototype.pushUnique = function(elem) {
if(this.indexOf(elem) == -1){
this.push(elem);
}
}
//filters are in OR, any one true will add, array result will be returned
Array.prototype.filterAny = function (filter,callback) {
var result = [];
this.forEach(function (row) {
for(var key in filter){
if(row[key]==filter[key]){
result.pushUnique(row);
}
}
});
if ('function' == typeof callback) {
callback(result);
} else {
return result
}
}
//filters are in AND, all true will add, array result will be returned
Array.prototype.filterAll = function (filter,callback) {
var result = [];
this.forEach(function (row) {
var status = 0;
for(var f1key in filter){
if(row[f1key]==filter[f1key]){
status++;
}
if (status==Object.keys(filter).length) {
result.pushUnique(row);
}
}
});
if ('function' == typeof callback) {
callback(result);
} else {
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment