2

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?

2
  • Nice problem, have you tried anything so far or have thought any ideas on how to attack it? Commented Jan 21, 2016 at 18:35
  • Thanks. After a while of searching around, reading documentation (lodash, underscore, plain JS, etc) to no avail, I tried looping through the initial array, checking to see if objects with the first and last values already exist in the new array, and if not pushing the new elements to the new array, but I'm not sure how to see if an object with multiple keys already exists in an array. Commented Jan 21, 2016 at 18:41

3 Answers 3

2

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

1 Comment

Clever! I didn't think of turning all the values for the keys of interest into one large string to search over. This worked!
1

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);

Comments

0

@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);
   }
});

Comments

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.