Lauren F Lauren F - 4 months ago 23
AngularJS Question

JavaScript: Remove duplicates of objects sharing same property value

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 specific
key:value
pair. It doesn't necessarily matter which object of the duplicates is copied to the new array.

For example, I want to trim based on the
price
property of
arrayWithDuplicates
, creating a new array that only includes one of each value:

var arrayWithDuplicates = [
{"color":"red",
"size": "small",
"custom": {
"inStock": true,
"price": 10
}
},
{"color":"green",
"size": "small",
"custom": {
"inStock": true,
"price": 30
}
},
{"color":"blue",
"size": "medium",
"custom": {
"inStock": true,
"price": 30
}
},
{"color":"red",
"size": "large",
"custom": {
"inStock": true,
"price": 20
}
}
];


Would become:

var trimmedArray = [
{"color":"red",
"size": "small",
"custom": {
"inStock": true,
"price": 10
}
},
{"color":"green",
"size": "small",
"custom": {
"inStock": true,
"price": 30
}
},
{"color":"red",
"size": "large",
"custom": {
"inStock": true,
"price": 20
}
}
];


Is there a JavaScript or Angular function that would loop through and do this?


EDIT: The property to filter on is nested within another property.

Answer

You can use underscore for this:

//by size:
var uSize = _.uniq(arrayWithDuplicates, function(p){ return p.size; });

//by custom.price;
var uPrice = _.uniq(arrayWithDuplicates, function(p){ return p.custom.price; });