Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript array flatting

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading