0

What's the cleanest and es6 native (if possible) way to loop through a object array to grab each unique value. Example would like this :

[{
"name" : "joe",
},
,{
"name" : "jean",
},
{
"name" : "joe",
},
{
"name" : "joe",
},
{
"name" : "mike", 
}]

and in my results I want to see only : joe, jean, mike (only unique values, no dupes)

3 Answers 3

6

Since you mentioned ES6, it seems like a Set object would be what you want since it will do the uniqueness part for you and should do so fairly efficiently:

var objs = [{"name" : "joe"},{"name" : "jean"},{"name" : "joe"},{"name" : "joe"},{"name" : "mike"}];

let uniqueNames = Array.from(new Set(objs.map(item => item.name)));
console.log(uniqueNames);

Run this snippet to see the results.

Sign up to request clarification or add additional context in comments.

Comments

3

a = [{name:"joe"},{name:"jean"},{name:"joe"},{name:"joe"},{name:"mike"}]

console.log(_.uniq(_.map(a, 'name')))           // Lodash 0.1.0

console.log([...new Set(a.map(o => o.name))])   // ES6
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Comments

1
var objs = [{"name" : "joe"},{"name" : "jean"},{"name" : "joe"},{"name" : "joe"},{"name" : "mike"}];
var uniqueNames = objs.map( obj => obj.name )
  .filter( (name, idx, arr) => { return arr.indexOf(name) === idx; } );

The .map extracts an array of the name values, and the .filter returns only the unique elements (first instances only).

1 Comment

fantastic, beautiful and simple

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.