JavaScript: Remove duplicates of objects sharing same property value

I have an array of objects that I would like to trim down based on a specific key:value pair. I want to create an array that includes only one object per this specific key:value pair. It doesn’t necessarily matter which object of the duplicates is copied to the new array.

For example, I want to trim based on the price property of arrayWithDuplicates, creating a new array that only includes one of each value:

var arrayWithDuplicates = [   {"color":"red",      "size": "small",     "custom": {       "inStock": true,       "price": 10     }   },   {"color":"green",      "size": "small",     "custom": {       "inStock": true,       "price": 30     }   },   {"color":"blue",      "size": "medium",     "custom": {       "inStock": true,       "price": 30     }   },   {"color":"red",      "size": "large",     "custom": {       "inStock": true,       "price": 20     }   } ]; 

Would become:

var trimmedArray = [   {"color":"red",      "size": "small",     "custom": {       "inStock": true,       "price": 10     }   },   {"color":"green",      "size": "small",     "custom": {       "inStock": true,       "price": 30     }   },   {"color":"red",      "size": "large",     "custom": {       "inStock": true,       "price": 20     }   } ]; 

Is there a JavaScript or Angular function that would loop through and do this?

EDIT: The property to filter on is nested within another property.

Add Comment
12 Answer(s)

You can use underscore for this:

//by size: var uSize = _.uniqBy(arrayWithDuplicates, function(p){ return p.size; });  //by custom.price; var uPrice = _.uniqBy(arrayWithDuplicates, function(p){ return p.custom.price; }); 
Add Comment

This function removes duplicate values from an array by returning a new one.

function removeDuplicatesBy(keyFn, array) {      var mySet = new Set();      return array.filter(function(x) {          var key = keyFn(x), isNew = !mySet.has(key);          if (isNew) mySet.add(key);          return isNew;      });  }    var values = [{color: "red"}, {color: "blue"}, {color: "red", number: 2}];  var withoutDuplicates = removeDuplicatesBy(x => x.color, values);  console.log(withoutDuplicates); // [{"color": "red"}, {"color": "blue"}]

So you could use it like

var arr = removeDuplicatesBy(x => x.custom.price, yourArrayWithDuplicates); 
Answered on July 16, 2020.
Add Comment

I don’t think there’s a built-in function in Angular, but it isn’t hard to create one:

function removeDuplicates(originalArray, objKey) {   var trimmedArray = [];   var values = [];   var value;    for(var i = 0; i < originalArray.length; i++) {     value = originalArray[i][objKey];      if(values.indexOf(value) === -1) {       trimmedArray.push(originalArray[i]);       values.push(value);     }   }    return trimmedArray;  } 

Usage:

removeDuplicates(arrayWithDuplicates, 'size'); 

Returns:

[     {         "color": "red",         "size": "small"     },     {         "color": "blue",         "size": "medium"     },     {         "color": "red",         "size": "large"     } ] 

And

removeDuplicates(arrayWithDuplicates, 'color'); 

Returns:

[     {         "color": "red",         "size": "small"     },     {         "color": "green",         "size": "small"     },     {         "color": "blue",         "size": "medium"     } ] 
Add Comment

Use Array.filter(), keeping track of values by using an Object as a hash, and filtering out any items whose value is already contained in the hash.

function trim(arr, key) {     var values = {};     return arr.filter(function(item){         var val = item[key];         var exists = values[val];         values[val] = true;         return !exists;     }); } 
Answered on July 16, 2020.
Add Comment

You can use lodash to remove duplicate objects:

 import * as _ from 'lodash';   _.uniqBy(data, 'id'); 

Here ‘id‘ is your unique identifier

Add Comment

Try the following function:

function trim(items){     const ids = [];     return items.filter(item => ids.includes(item.id) ? false : ids.push(item.id)); } 
Answered on July 16, 2020.
Add Comment

using lodash you can filter it out easily

the first parameter will be your array and second will be your field with duplicates

_.uniqBy(arrayWithDuplicates, 'color') 

it will return an array with unique value

Add Comment

Simple solution although not the most performant:

var unique = []; duplicates.forEach(function(d) {     var found = false;     unique.forEach(function(u) {         if(u.key == d.key) {             found = true;         }     });     if(!found) {         unique.push(d);     } }); 
Add Comment
for (let i = 0; i < arrayWithDuplicates.length; i++) {      for (let j = i + 1; j < arrayWithDuplicates.length; j++) {        if (arrayWithDuplicates[i].name === students[j].name) {           arrayWithDuplicates.splice(i, 1);        }      }     }  this will work perfectly...and this will delete first repeated array. To delete last repeated array we only have to change  arrayWithDuplicates.splice(i, 1) ; into  arrayWithDuplicates.splice(j, 1); 
Answered on July 16, 2020.
Add Comment

Off the top of my head there is no one function that will do this for you as you are dealing with an array of objects and also there is no rule for which duplicate would be removed as duplicate.

In your example you remove the one with size: small but if you were to implement this using a loop you’d most likely include the first and exclude the last as you loop through your array.

It may very well be worth taking a look at a library such as lodash and creating a function that uses a combination of it’s API methods to get the desired behaviour you want.

Here is a possible solution you could use making use of basic Arrays and a filter expression to check whether a new item would be considered a duplicate before being attached to a return result.

var arrayWithDuplicates = [     {"color":"red", "size": "small"},     {"color":"green", "size": "small"},     {"color":"blue", "size": "medium"},     {"color":"red", "size": "large"} ];  var reduce = function(arr, prop) {   var result = [],       filterVal,       filters,       filterByVal = function(n) {           if (n[prop] === filterVal) return true;       };   for (var i = 0; i < arr.length; i++) {       filterVal = arr[i][prop];       filters   = result.filter(filterByVal);       if (filters.length === 0) result.push(arr[i]);   }   return result; };  console.info(reduce(arrayWithDuplicates, 'color')); 

You can check out some literature on Array filtering here If you need to provide a preference on which item to remove you could define extra parameters and logic that will make extra property checks before adding to a return value.

Hope that helps!

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.