I have an object like so:
{ green: 2, blue: 1, red: 2}
How can I turn it into an array that looks like this:
[ 'green', 'green', 'blue', 'red', 'red']
Could be done like this:
Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k));
Example:
const obj = { green: 2, blue: 1, red: 2}; const res = Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k)); console.log(res);
1.4m articles
1.4m replys
5 comments
57.0k users