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

Best way to create an array from an object that has number of copies

From an object like this:

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

I would like to turn into

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

Where the key is the string and the value is the number of copies, order doesn’t matter.

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

What’s the best way to do this?

I was thinking about using array.fill but not sure if that’s actually easier than just iterating and push.

Edit: Currently this:

const arr = []
_.each(obj, function (v, k) {
  _.times(v, function () {
    arr.push(k)
  })
})

>Solution :

You could flatMap the Object.entries and fill an array of each size.

const obj = { a: 1, b: 2, c: 3 };
const result = Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k));

console.log(result)

or with Lodash

const obj = { a: 1, b: 2, c: 3 };
const arr = _.flatMap(obj, (v,k) => Array(v).fill(k))

console.log(arr);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

But there’s nothing like a simple loop

const obj = { a: 1, b: 2, c: 3 };
const result = []

for (let [k, v] of Object.entries(obj)) {
  while (v--) {
    result.push(k)
  }
}

console.log(result)
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