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!
2
Answers
There is an almost one-liner for it, but you could also be more explicit.
Here it is. It uses a lot of
map
,reduce
, andfilter
to do the process successfully.At first, it unnests the array by mapping the
.colors
attribute of any of thecars
. It thenreduce
s the array even further to unnest the arrays themselves.It turns it into this unnested array.
From there on it gains the dupes, the
filter
getting all the duplicate values, and theSet
to make sure there is only one of each dupe. E.g. thefilter
would output['green', 'green']
. Putting thefilter
into aSet
outputs just['green']
.