Home > Mobile >  JavaScript array flatting
JavaScript array flatting

Time:02-10

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' ]
]

CodePudding user response:

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)

CodePudding user response:

You don't need reduce. You can simply pass all the colours arrays to concat() with argument spreading.

let colours_array = [].concat(...colours.map(el => el.colours));

Then see Remove duplicate values from JS array for how to get just the unique colours from this result.

CodePudding user response:

 let 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 distinct =(value,index,self)=>{return self.indexOf(value)===index;};

console.log(colours.reduce((acc, curVal) => {
        return acc.concat(curVal.colours)
    }, []).filter(distinct));

  • Related