DorianHuxley DorianHuxley - 5 months ago 10
Javascript Question

Return unique array values from an array inside an array of objects

I can't find a similar question and I'm a bit stuck. I have the following JSON array:

[
{
"Name": "element1",
"Attributes": ["1", "2"]
},

{
"Name": "element2",
"Attributes": ["1","3" ]
},
{
"Name": "element3",
"Attributes": []
}
]


I'm trying to create an array of all the unique elements in the "Attributes" property, but I'm having trouble looping through each object, and then looping through the array elements to return the unique values. I'm trying to do it with filter(), or map() preferably.

EDIT: I want an array of unique elements, so: [1,2,3].

Answer

You could do it with couple of Array methods. For example:

var result = [
    {
        "Name": "element1",
        "Attributes": ["1", "2"]
    },

    {
        "Name": "element2",
        "Attributes": ["1","3" ]
    },
    {
        "Name": "element3",
        "Attributes": []
    }
]

// map to [ ["1", "2"], ["1", "3"], [] ]
.map(item => item.Attributes)

// flatten to [ "1", "2", "1", "3" ]
.reduce((prev, curr) => {
  return prev.concat.apply(prev, curr)
}, [])

// filter unique [ "1", "2", "3" ]
.filter((item, i, arr) => arr.indexOf(item) === i)

console.log(result)