Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessekinsman/b9052bfd812aebd5bb7f3b8deac94f90 to your computer and use it in GitHub Desktop.
Save jessekinsman/b9052bfd812aebd5bb7f3b8deac94f90 to your computer and use it in GitHub Desktop.
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