Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Returns a new array with objects that have a unique value by the prop that is passed to it.
// Prop is the prop you want to check in the array for a unique value
// objectArray is the original array of objects
function deDupeArrByPropReduce(objectArray, prop) {
return objectArray.reduce(function (acc, obj, ind, arr) {
// acc is the accumulator. On line 14 we pass an emtpy array as the inital value
if (acc.findIndex(obj1 => {
// We check if the accumulator has an object with the same value as the iterated obj.
return obj1[prop] === obj[prop];
}) == -1) {
// if the findIndex function returns -1 we add the object to the accumulator
acc.push(obj);
}
return acc;
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment