Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates from JSON array by a value in each JSON object in array

If there are two JSON objects in an array with same value for a particular field, then I want to mark them as duplicate. I want to remove one of them. Similarly, when there are multiple duplicate, I only want to keep the last object(latest).If this is input:

names_array = [
    {name: "a",  age: 15},
    {name: "a",  age: 16},
    {name: "a",  age: 17},
    {name: "b",  age: 18}
    {name: "b",  age: 19}];

I want the output to be

names_array_new = 
    {name: "a",  age: 17},
    {name: "b",  age: 19}];

I have searched for this but only found how to remove duplicates when entire objects are same.

like image 896
SS306 Avatar asked Sep 02 '25 04:09

SS306


1 Answers

This should do it:

names_array = [
    {name: "a",  age: 15},
    {name: "a",  age: 16},
    {name: "a",  age: 17},
    {name: "b",  age: 18},
    {name: "b",  age: 19}];

function hash(o){
    return o.name;
}    

var hashesFound = {};

names_array.forEach(function(o){
    hashesFound[hash(o)] = o;
})

var results = Object.keys(hashesFound).map(function(k){
    return hashesFound[k];
})

The hash function decides which objects are duplicates, the hashesFound object stores each hash value together with the latest object that produced that hash, and the results array contains the matching objects.

like image 115
codebox Avatar answered Sep 04 '25 21:09

codebox