0

I have an object array:

var objects = [
  {'key1': '1', 'key2': '2'},
  {'key1': '3'},
  {'key1': '4', 'key2': '5', 'key3': '6'},
  {'key1': '1', 'key2': '2'},
  {'key1': '3'},
  {'key1': '4', 'key2': '5', 'key3': '6'},
];

I want an array with unique values of key2 but without any undefined values in it. Something like this:

['2', '5']

Right now, I'm using:

lodash.without(lodash.uniq(lodash.map(objects, 'key2')), undefined)

My Question:

Is there a better and more compact way to do this?

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110

2 Answers2

2
objects.reduce(function(m,d){
    if(d.key2 != undefined && m.indexOf(d.key2)<0){
        m.push(d.key2)
    }
    return m;
},[])
Chirag Ravindra
  • 4,760
  • 1
  • 24
  • 35
  • How do we compare the performance of this approach against mine? – SiddAjmera Jun 27 '17 at 09:56
  • 1
    There are many ways to measure your code's performance. You can use profilers, log timestamps and on to more advanced options. You can start here: https://www.sitepoint.com/measuring-javascript-functions-performance/ https://stackoverflow.com/questions/111368/how-do-you-performance-test-javascript-code – Chirag Ravindra Jun 27 '17 at 10:10
  • Great. That helps. Unlike Callum's comment that doesn't. – SiddAjmera Jun 27 '17 at 10:14
  • Hey Chirag, thanks. This is Infact, faster than my approach. – SiddAjmera Jun 27 '17 at 15:18
1

You could use Set and filter the object before making the values unique.

var objects = [{ key1: '1', key2: '2' }, { key1: '3' }, { key1: '4', key2: '5', key3: '6' }, { key1: '1', key2: '2' }, { key1: '3' }, { key1: '4', key2: '5', key3: '6' }],
    unique = [...new Set(objects.filter(o => 'key2' in o).map(o => o.key2))];

console.log(unique);

ES5

var objects = [{ key1: '1', key2: '2' }, { key1: '3' }, { key1: '4', key2: '5', key3: '6' }, { key1: '1', key2: '2' }, { key1: '3' }, { key1: '4', key2: '5', key3: '6' }],
    values = objects.reduce(function (r, o) {
        ('key2' in o) && (r[o.key2] = true);
        return r;
    }, Object.create(null));
    unique = Object.keys(values);

console.log(unique);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    I don't shure that ecma 2015 solution is suitable if pointed that lodash is used. – YD1m Jun 27 '17 at 09:52
  • @YD1m why not? lodash also uses ES2015: [just one example](https://github.com/lodash/lodash/blob/master/.internal/baseFlatten.js#L28) – Thomas Jun 27 '17 at 10:46