e.g
obj = {a:2, b:3, c:1}
The transformed array is:
['a','a','b','b','b','c']
You can do it using reduce
:
const obj = {a:2, b:3, c:1};
const res = Object.keys(obj).reduce((arr, key) => {
return arr.concat( new Array(obj[key]).fill(key) );
}, []);
console.log(res); // ["a","a","b","b","b","c"]
Explanation:
Object.keys()
returns an array of all the keys: ["a", "b", "c"]
We then loop over them with reduce
, and while doing so, we build an array. For every key, we create a new array with the same length as the value, and fill it with the key (a
, b
...).
We then concatenate them together with concat
.
Get entries and take a flat map with an array of a wanted length and fill the array with the key.
const
object = { a: 2, b: 3, c: 1 },
result = Object
.entries(object)
.flatMap(([key, value]) => Array(value).fill(key));
console.log(result);
Try:
let obj = { a:2, b:3, c:1 }
let newObj = [];
for (var key in obj) {
while (obj[key]) {
newObj.push(key);
obj[key]--;
}
}
console.log(newObj);