i need to get every unique color in the array below fit in one single array
const colours = [{
mood: "happy",
fish: "robin",
colours: ["blue", "green"]
},
{
mood: "tired",
fish: "panther",
colours: ["green", "black", "orange", "blue"]
},
{
mood: "sad",
fish: "goldfish",
colours: ["green", "red"]
}
];
console.log(colours.map(e => {
let flatArray = e.colours.reduce((acc, curVal) => {
return acc.concat(curVal)
}, []);
return flatArray
}))
It currently outputs:
[
[ 'blue', 'green' ],
[ 'green', 'black', 'orange', 'blue' ],
[ 'green', 'red' ]
]
>Solution :
Not sure if this is what you’re after, but this will create a single array of unique colors.
let unique = [...new Set(colours.flatMap(c => c.colours))]
flatMap() allows us to cycle through and create a one dimensional array of the existing colours, while [...new Set(array)] lets us strip out duplicates
colours = [{
mood: "happy",
fish: "robin",
colours: ["blue", "green"]
},
{
mood: "tired",
fish: "panther",
colours: ["green", "black", "orange", "blue"]
},
{
mood: "sad",
fish: "goldfish",
colours: ["green", "red"]
}
]
let unique = [...new Set(colours.flatMap(c => c.colours))]
console.log(unique)