1

Write a function that takes in an object like so {1: 4, 2: 10, 5:3} and then return a list of all the numbers described in the object. Each key-value pair describes a number and how many times it should occur in the array.

Example: {3 : 10,5 : 2}

[3,3,3,3,3,3,3,3,3,3,5,5]

Also account for empty, null, undefined and non-objects in your code that can be passed in

In those cases just return [], the empty list

Here's what I've been able to produce for. I know I have to do a second loop, but I don't understand how to make the numbers appear in the array the number of times described. Here's my progress:

    var numObj = {1:4, 2:10, 3:5};

    function numDescribed(numObj) {
       var numOfNums = [];
       for (var x in numObj) {
          numOfNums.push(numObj[x]); //this produces an array of [4, 10, 5]
       } for (var i = 0; i < numOfNums.length; i++) {
        numOfNums.
       }
    }
zasman
  • 446
  • 1
  • 8
  • 28

1 Answers1

0

var obj = { 3: 10, 5: 2 };

var res = [];

Object.keys(obj).forEach(function(e) {
    for (var i = 0; i < obj[e]; i++) {
        res.push(e);
    }
});

document.write(res);
isvforall
  • 8,768
  • 6
  • 35
  • 50