The main goal is to select all the colors that every car.colors contain, if there’s no color that every car have then the expected output is an empty array.
Having an array that contains text, and a cars array:
const color = ['green','red']
const cars = [
{id:1, colors: ['green']},
{id:2, colors: ['green','red']},
{id:3, colors: ['blue','green']}
]
The expected output is:
const colorsThatEveryCarHave = ['green'];
Already tried to every, filter, map, flatMap, and reduce, but because of the cars nested array my every tries failes.
Every help would appreciated!
1
There is an one-liner for it, but you could also be more explicit.
cars.reduce((s, {colors}) => s.intersection(new Set(colors)), new Set(color))
// Set {"green"}
1
const cars = [
{
id: 1,
colors: ['green']
},
{
id: 2,
colors: ['green', 'red']
},
{
id: 3,
colors: ['blue', 'green']
},
]
const unnested = cars
.map(a => a.colors)
.reduce(
(nestedArr, currentValue) => [...nestedArr, ...currentValue]
);
const colorsThatEveryCarHas = [...new Set(unnested
.filter(
(a, index) => unnested.indexOf(a) != index
))];
console.log(cars)
console.log(unnested)
console.log(colorsThatEveryCarHas)
Here it is. It uses a lot of map, reduce, and filter to do the process successfully.
At first, it unnests the array by mapping the .colors attribute of any of the cars. It then reduces the array even further to unnest the arrays themselves.
It turns it into this unnested array.
[
"green",
"green",
"red",
"blue",
"green"
]
From there on it gains the dupes, the filter getting all the duplicate values, and the Set to make sure there is only one of each dupe. E.g. the filter would output ['green', 'green']. Putting the filter into a Set outputs just ['green'].
Since we are filtering out colors that are not present in every cars colors array this was my idea using filter and every built-in methods of arrays:
const color = ['green','red'];
const cars = [
{id:1, colors: ['green']},
{id:2, colors: ['green','red']},
{id:3, colors: ['blue','green']}
];
const colorsThatEveryCarHave = color.filter(col => cars.every(car => car.colors.includes(col)));
console.log(colorsThatEveryCarHave);
