Last active
December 27, 2016 11:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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