Last active
March 28, 2019 17:20
-
-
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.
This file contains 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
// 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