Skip to content Skip to sidebar Skip to footer

How To Get Unique Objects From Objects Array In Javascript

I have an array of objects that looks like the image below. Is there a way by which I can have an array that contains unique objects with respect to id ? We can see below that the

Solution 1:

To get an array of "unique" objects(with last index within the list) for your particular case use the following approach (Array.forEach, Array.map and Object.keys functions):

// exemplary array of objects (id 'WAew111' occurs twice)var arr = [{id: 'WAew111', text: "first"}, {id: 'WAew222', text: "b"}, {id: 'WAew111', text: "last"}, {id: 'WAew33', text: "c"}],
    obj = {}, new_arr = [];

// in the end the last unique object will be considered
arr.forEach(function(v){
    obj[v['id']] = v;
});
new_arr = Object.keys(obj).map(function(id) { return obj[id]; });

console.log(JSON.stringify(new_arr, 0, 4));

The output:

[{"id":"WAew111","text":"last"},{"id":"WAew222","text":"b"},{"id":"WAew33","text":"c"}]

Solution 2:

The best way to do this is to modify your data structure into an object itself where each key is one of the IDs:

{
    "WadWA7WA6WAaWAdWA...": {
        "text": "birla"
    },
    "WadWA...": {
        "test": "ab"
    }
}

and so forth. If the data comes from a source formatted that way, you can always map the array of results to this format.

Solution 3:

You could create a hash using the id as the key and keeping the value as the entire object:

var myHash = newObject();
var i;

for(i = 0; i < yourArray.length; i++) {
    var yourObjId = yourArray[i][id];
    myHash[yourObjId] = yourArray[i];
}

You would be left with a hash myHash containing objects with unique id's (and only the last object of duplicates would be stored)

Solution 4:

Try this: just add to a new object using id as the key

var arr = [{id:'123', text: 'a'}, {id:'234', text: 'b'}, {id:'123', text: 'c'}]; 
varmap = new Object();
for(var i in arr){ map[arr[i].id] = arr[i]; }
var newArr = [];
for(var i in map){ newArr.push(map[i]); }

newArr shall contain the 2nd and 3rd object.

Post a Comment for "How To Get Unique Objects From Objects Array In Javascript"