Javascript - get unique values from an array inside object

Viewed 130

I'm trying to retrieve all unique values from an array inside and object, inside an array

var items = [
{
  colors:['white', 'black'],
  fruits:['apple, banana']
},

{
  colors:['yellow', 'black'],
  fruits:['mango, blueberry'],
},
...
]

const property = 'colors'
const values = this.distinct(this.items.map(item => item[property].map(elem => elem))

I want the values to return an array with each value of colors so, like this:

['black','white','yellow']

But it's not working, and I don't understand why

2 Answers

flatMap the array of objects to extract each colors sub-array, pass into the Set constructor to de-duplicate, and turn the Set back into an array:

var items = [{
  colors:['white', 'black'],
  fruits:['apple, banana']
},{
  colors:['yellow', 'black'],
  fruits:['mango, blueberry'],
}];
const colorsSet = new Set(
  items.flatMap(item => item.colors)
);
const uniques = [...colorsSet];
console.log(uniques);

reduce can be used to iterate through array and assign a color as key of accumulator object:

const result = items.reduce((a, {colors})=> {
    colors.forEach(cl => a[cl] = 1);
    return a;
}, {})
console.log(Object.keys(result));

Or one line way:

Object.keys(items.reduce((a, {colors})=> (colors.forEach(cl => a[cl] = 1) , a), {}));

Read more about reduce method

An example:

let items = [
    {
        colors: ['white', 'black'],
        fruits: ['apple, banana']
    },

    {
        colors: ['yellow', 'black'],
        fruits: ['mango, blueberry'],
    }
]

const result = items.reduce((a, {colors})=> {
    colors.forEach(cl => a[cl] = 1);
    return a;
},{})
console.log(Object.keys(result));

const oneLine = Object.keys(items.reduce((a, {colors})=> 
    (colors.forEach(cl => a[cl] = 1) , a), {}));
console.log(oneLine);

Related