I have an array of objects that I would like to trim down based on a specific key:value
pair. I want to create an array that includes only one object per this s
Use Array.filter()
, keeping track of values by using an Object
as a hash, and filtering out any items whose value is already contained in the hash.
function trim(arr, key) {
var values = {};
return arr.filter(function(item){
var val = item[key];
var exists = values[val];
values[val] = true;
return !exists;
});
}