Array for loop and sort

Remove objects from array that contain the same value for the same prop using a for loop and sort

by jessekinsman

JavaScript

function deDupeArrByPropForLoopSort(objectArray, prop) {
  // create a new array that will be returned
  const returnArr = [];
  // copy the parameter array so as to not mutate it
  const sorted = Object.assign([], objectArray);
  // Sort by the prop
  sorted.sort(function(a, b){
    if (a.age > b.age) {
      return -1;
    } else {
      return 1;
    }
  });
  // Add the first element
  returnArr.push(Object.assign({}, sorted[0]));
  // Loop through the sorted array and check if the last object contained the same prop value as the current item
  for (let i = 1; i < sorted.length; i+=1) {
    if (sorted[i][prop] !== sorted[i-1][prop]) {
      // if they do not match, add to the new array
      returnArr.push(Object.assign({}, sorted[i]));
    }
  }
  // return the new array
  return returnArr;
}