Search code examples
javascriptreactjsunderscore.jslodash

How to compare each object in an array with each other. When found update the object with a new property


For example consider the following array with objects.

var collection = [{name:'user1',phone:'203'},
                  {name:'user2',phone:'5050'},
                  {name:'user1',phone:'203'}]

Now I want to compare the each object with each other and give the result as.

var newCollection =   {name:'user1',phone:'203', rowMatch:'true'},
                      {name:'user2',phone:'5050', rowMatch:'false'},
                      {name:'user1',phone:'203',rowMatch:'true'}

So, I want the new collecition like this where it compares and updates with new property when object properties match like the first and third object.


Solution

  • You can use newCollection or manipulate in the collection like this

    collection.forEach((item)=>{
    item.rowMatch = (collection.filter((e)=>{return (e.name==item.name&&e.phone==item.phone)}).length>1)?'true':'false';
    })
    console.log(collection)
    

    Simple is that.Here is working JSFiddle for it https://jsfiddle.net/touqeer/pgdsw9Le/1/ .