13

I only recently discovered the power of underscore.js, still new to the methods I kindly ask for a suggestion:

How do I get from this:

[
    [{
        "name": "Type 2",
        "id": 14
    }],
    [{
        "name": "Type 1",
        "id": 13
    }, {
        "name": "Type 3",
        "id": 15
    }],
    [{
        "name": "Type 2",
        "id": 14
    }],
    [{
        "name": "Type 1",
        "id": 13
    }]
]

to this:

["Type 1","Type 2","Type 3"]

i.e. no duplicated and "name" property only.

Any suggestions much appreciated.

Iladarsda
  • 10,640
  • 39
  • 106
  • 170

5 Answers5

28
_(data).chain().flatten().pluck('name').unique().value()

(Convert the nested lists to a flat one, pick name from each of the objects in the list, and make it unique.)

Jakub Roztocil
  • 15,930
  • 5
  • 50
  • 52
  • 1
    Is there any particular merit to chaining methods in underscore/lo-dash compared to nesting (as in McGarnagle's answer). Or is it purely for aesthetics/code clarity? – nverba Jul 08 '14 at 10:09
  • In lodash it is more efficient if you create a wrapper with `_()` if you chain multiple methods together, less efficient if you only do one (maybe two) operations. Do your own benchmarks for each situation. – kmiyashiro Mar 11 '15 at 23:38
10
  • Use flatten first, to convert the nested array to a flat array.
  • Then pluck to get the "name" values as an array
  • Finally uniq

_.uniq(_.pluck(_.flatten(items), "name"))

Fiddle

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
3
_.uniq(_.pluck(x,'name'));

the above code is sufficient for extracting different "name" attribute

JDurstberger
  • 4,127
  • 8
  • 31
  • 68
2
var arr = _.uniq(_.map(_.flatten(array), function(e) {
    return e.name;
}));
Alex_Crack
  • 710
  • 1
  • 4
  • 14
1

Simple way:

1. use _.map to get all the names

var names = _.map(items, function(item) { return item.name});

2. Get the _.uniq from that names

var uniqueNames = _.uniq(names);