Reputation: 2915
I have an array of javascript objects. Here is an example:
[{'first': 'Mary', 'last':'Smith', 'task':'managing'},
{'first': 'Mary', 'last':'Smith', 'task':'research'},
{'first': 'Henry', 'last':'Ford', 'task':'assembling'},
{'first':'Henry', 'last':'Winkler', 'task':'acting;}]
and I want to find all elements in the array that are distinct in first AND last name. The output I'm looking for is of the form:
[{'first': 'Mary', 'last':'Smith'},
{'first': 'Henry', 'last':'Ford'},
{'first': 'Henry', 'last':'Winkler'}]
How do I do this in javascript?
Upvotes: 2
Views: 62
Reputation: 145
@Minusfour You are just ahead of me. I got same solution.
array.forEach( function (arrayItem)
{
if(hashMap[arrayItem.first + arrayItem.last] == 0){
hashMap[arrayItem.first + arrayItem.last] = 1;
finalArray.push(arrayItem);
}
});
Upvotes: 0
Reputation: 21005
This would be a good time to roll out the new ES6 set
var s = new Set();
arr.forEach(a => s.add({'first':a.first, 'last': a.last}))
var myArr = Array.from(s);
Upvotes: 1
Reputation: 14423
I would use a Map
for this:
var m = new Map();
arr.forEach(function(obj){
var name = obj.first + ' ' + obj.last;
if(!m.has(name)){
m.set(name, { first : obj.first, last : obj.last});
}
});
var uniques = Array.from(m.values());
Upvotes: 2