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!

0

1 Answer 1

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];
});
Sign up to request clarification or add additional context in comments.

10 Comments

can you explain this sir?
there's an error that says 'Invalid left-hand side in assignment' for the line return !temp[obj.name] && temp[obj.name] = true;
@LewJasonNuyda: Operator precedence. Use return !temp[obj.name] && (temp[obj.name] = true); instead.
@FelixKling Yeah, I forget about precedence
@FelixKling Done, explanation is added.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.