0

EDITED!!

I have an object array:

Array 0:[{id:"a1" , code:"123" , name:"a"},
         {id: "a2", code: "222" , name: "a"},
          {id: "b1", code: "433", name: "b"}]
Array 1:[{id:"a1" , code:"123" , name:"a"},
         {id: "b2", code: "211" , name: "b"},
          {id: "b1", code: "433", name: "b"}]

I want to get the array of object that has no duplicate value for "name". and store it to another array:

Result:
Array 0:{id: "b1", code: "433", name:"b"}
Array 1: {id:"a1" , code:"123" , name:"a"}

How can I get the array of object that has no duplicate value for name ? All I found on some thread is to remove duplicates from array and not get the array with no duplicate. Thanks in advance!

1 Answers1

1
function filterByName(array) {
    var counts = {};

    array.forEach(function(obj) { 
        counts[obj.name] ? ++counts[obj.name] : (counts[obj.name] = 1);
    });

    return array.filter(function(obj) { 
        return counts[obj.name] === 1;
    });
}

var filteredArray1 = filterByName(array1);
var filteredArray2 = filterByName(array2);

Explanation of function

  1. Create temporary counts object for keeping counts of object with the same name.
  2. Fill this object with data by using standard forEach method of array.
  3. Filter array by using standard filter method

UPD You need this if I understand your question correctly at last:

var filteredArray = arrayOfArrays.map(function(arrayOfObjects) {
  return filterByName(arrayOfObjects)[0];
});
alexpods
  • 47,475
  • 10
  • 100
  • 94