0

e.g

obj = {a:2, b:3, c:1}

The transformed array is:

['a','a','b','b','b','c']

Zed
  • 1

3 Answers3

0

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.

blex
  • 23,736
  • 5
  • 39
  • 70
0

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);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

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);
adiga
  • 31,610
  • 8
  • 53
  • 74
Kishan
  • 1,470
  • 10
  • 17
  • 1
    [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/questions/358992) – adiga Jun 21 '20 at 20:24