Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
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' ]
]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

 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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!