Mark Mark - 1 month ago 11
Javascript Question

Get unique strings from array of array of objects

I have an array which contains arrays of objects. I want to get the unique property values from the array. E.g.

var array = [
[
{
a: 'ggg'
},
{
a: 'kkk'
}
],
[
{
a: undefined
}
],
[
{
a: 'ddd'
}
],
[
{
a: 'ggg'
}
]
];


Would return:

['ggg', 'kkk', 'ddd']


Im using the underscore library, heres what I tried:

var list = _.reduce(arr, function(memo, v, k) {
memo.concat(_.pluck(v, 'a'));
return memo;
}, []);

console.log('list is ', list);

console.log(_.uniq(list));


But its not working. The fiddle is here.

Answer

Here's a solution using Underscore's flatten, reject, pluck and uniq:

var result = _.chain(array)
    .flatten()
    .pluck('a')
    .reject(_.isUndefined)
    .uniq()
    .value();
Comments