ni8mr ni8mr - 5 months ago 8
Javascript Question

Removing elements from an array of objects based on duplicate values of multiple keys

I have an array of objects like this -

var arr = [
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"false", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4}
];


I want to remove the duplicates having same type_id and full_empty values. The result should look like this -

var arr = [
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"false", quantity:4},
];


I have searched and found some solution, but some of them are for removing duplicate keys or for removing duplicates based on duplicate value of only one key. Some required external libraries. Also there are some solutions which i can't understand. Is there any easy way to do this in plain JavaScript ?

Edit for better understand - I have read this answer . Accepted answer is for finding duplication for only one key. In my case, i have to find the duplication for multiple keys.

Answer

You can use pure functions by using Array.some() and Array.reduce() to reduce your input array to array of distinct elements as shown below

    var arr = [
        { type_id: "3", full_empty:"true", quantity:1},
        { type_id: "3", full_empty:"true", quantity:1},
        { type_id: "9", full_empty:"true", quantity:4},
        { type_id: "9", full_empty:"false", quantity:4},
        { type_id: "9", full_empty:"true", quantity:4},
        { type_id: "9", full_empty:"true", quantity:4},
        { type_id: "9", full_empty:"true", quantity:4}
    ];

    var a = arr.reduce(function (accumulator, current) {
      if (checkIfAlreadyExist(current)) {
        return accumulator
      } else {
        return accumulator.concat([current]);
      }
      
      function checkIfAlreadyExist(currentVal) {
        return accumulator.some(function(item){
          return (item.type_id === currentVal.type_id &&
                  item.full_empty === currentVal.full_empty);
        });
      }
    }, []);
        
    console.log(a);