skip to Main Content

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


  1. There is an almost one-liner for it, but you could also be more explicit.

    cars.slice(1).reduce(
      (s, {colors}) => s.intersection(new Set(colors)), 
      new Set(cars[0].colors)
    )
    // Set {"green"}
    
    Login or Signup to reply.
  2. 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'].

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search