Array.filter and sort

Remove objects from array that contain the same value for a specific prop using array.filter and sort

by jessekinsman

JavaScript

function deDupeArrByPropFilter(objectArray, prop) {
  // copy the array parameter
  const sorted = Object.assign([], objectArray);
  // sort the new array by the prop
  sorted.sort(function(a, b){
    if (a[prop] > b[prop]) {
      return -1;
    } else {
      return 1;
    }
  });
  // return a new array from array filter
  return sorted.filter(function (item, ind, arr) {
    // Check if the previous item has the same prop value as the current item
    if (ind !== 0) {
      return arr[ind-1][prop] !== item[prop];
    } else {
      // return first element
      return true;
    }
  });
}