2

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

0

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.