Array.reduce and sort

Array remove object with duplicate prop value by array.reduce and sort

by jessekinsman

JavaScript

function deDupeArrByPropReduceSort(objectArray, prop) {
  //copy the parameter array as we don't want to mutate that object
  const sorted = Object.assign([], objectArray);
  // Now we sort the new array by the prop value
  sorted.sort(function(a, b){
    if (a[prop] > b[prop]) {
      return -1;
    } else {
      return 1;
    }
  });
  // return the accumulator from the reduce function that is called on the new sorted array
  return sorted.reduce(function (acc, obj, ind, arr) {
    // Check that the last element in the accumulator does not contain the same prop value as the iterated object
    if (acc[acc.length-1][prop] !== obj[prop]) {
      // add the iterated object, if it is not found in the accumulator
      acc.push(obj);
    }
    return acc;
  }, [sorted[0]]);
}