shivakb
2/2/2018 - 2:51 AM

Remove duplicates from an array of objects in javascript

Removes duplicates objects from array

//  FUN METHOD
/**
 * Remove duplicates from an array of objects in javascript
 * @param arr - Array of objects
 * @param prop - Property of each object to compare
 * @returns {Array}
 */
function removeDuplicates( arr, prop ) {
  let obj = {};
  return Object.keys(arr.reduce((prev, next) => {
    if(!obj[next[prop]]) obj[next[prop]] = next; 
    return obj;
  }, obj)).map((i) => obj[i]);
}

//  FUN METHOD COMPRESSED - 147 bytes
/*
function removeDuplicates(e,n){var o={};return Object.keys(e.reduce(function(e,r){return o[r[n]]||(o[r[n]]=r),o},o)).map(function(e){return o[e]})}
*/

//  MORE EFFICIENT, BUT LESS FUN
/**
 * Remove duplicates from an array of objects in javascript
 * @param arr - Array of objects
 * @param prop - Property of each object to compare
 * @returns {Array}
 */
function removeDuplicates( arr, prop ) {
  var obj = {};
  for ( var i = 0, len = arr.length; i < len; i++ ){
    if(!obj[arr[i][prop]]) obj[arr[i][prop]] = arr[i];
  }
  var newArr = [];
  for ( var key in obj ) newArr.push(obj[key]);
  return newArr;
}

//  MORE EFFICIENT, BUT LESS FUN COMPRESSED - 143 bytes
/*
function removeDuplicates(e,r){for(var n={},o=0,t=e.length;t>o;o++)n[e[o][r]]||(n[e[o][r]]=e[o]);var u=[];for(var c in n)u.push(n[c]);return u}
*/