HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Generating an array of unique values of a specific property in an object array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uniquearraygeneratingpropertyspecificvaluesobject

Problem

Given a table represented as a javascript array of objects, I would like create a list of unique values for a specific property.



var table = [
{
a:1,
b:2
},
{
a:2,
b:3
},
{
a:1,
b:4
}
];

var groups = _.groupBy(table, "a");
var array = [];
_.forOwn(groups, function(value, key){
array.push(key);
});

console.log(array);


Check your console




The problems with this code is that the groupBy keep track of the values, which I really don't care about, and I need to iterate over the entire list generated by group again so I can yank out the keys. It seems pretty inefficient to me and Im wondering if there is a smarter way to do this without reinventing the wheel (or perhaps if I should just bite the bullet and reinvent the wheel).

Solution

I know this is an old post but purely for those looking for ways to do this heres a way that I found works nicely with a single line



var table = [
{
a:1,
b:2
},
{
a:2,
b:3
},
{
a:1,
b:4
}
];

let result = [...new Set(table.map(item => item.a))];
document.write(JSON.stringify(result));

Context

StackExchange Code Review Q#100768, answer score: 7

Revisions (0)

No revisions yet.