Anudeep Anudeep - 1 month ago 11
Javascript Question

How to collect all array unique values from array of objects using underscore?

I have an array of objects. Like

project=[
{
name : "A"
dept : ["a", "b", "c"]
},
{
name : "B"
dept : ["a", "e", "f", "g"]
},
{
name : "C"
dept : ["b", "c", "e", "j"]
},
]


Now I want to collect all unique array values of dept from this array of object using underscore.
The output should be save in a new array. Like

var newArray = ["a", "b", "c", "e", "f", "g", "j"]


I am new in underscore.js. Thanks in advance.

Answer
var project = [{
    name: "A",
    dept: ["a", "b", "c"]
}, {
    name: "B",
    dept: ["a", "e", "f", "g"]
}, {
    name: "C",
    dept: ["b", "c", "e", "j"]
}, ]



_UNIQUEAGEARRAY = _.flatten(project.map(function(item) {
    return item.dept
}));

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

document.body.innerHTML = JSON.stringify(_UNIQUEAGEARRAY);

A Fiddle:

http://jsfiddle.net/7k3ewb49/

Comments