0

I want to fill an not completed array. I will show an example:

var main = [
{ "id":"0", "value":500 },
{ "id":"3", "value":300 }
]

var fill = []


for (i = 0 ; i < main.length; i++){
    fill[main[i].id] = main[i].value
}

console.log(fill)

How do i fill these empty arrays with 0 ?

Thanks!

2
  • 1
    fill[main[i].id] = 0 ? Commented Oct 5, 2017 at 15:51
  • 1
    Possible duplicate of default array values Commented Oct 5, 2017 at 15:52

3 Answers 3

1

if you dont know how long the array is, i would do it like this

 var main = [
{ "id":"0", "value":500 },
{ "id":"3", "value":300 }
]

var fill = []
for (var i = 0 ; i < main.length; i++){
    fill[main[i].id] = main[i].value
}
for (var j = 0 ; j < fill.length; j++){
    if(fill[j] === undefined){
        fill[j] = 0
    }
}
console.log(fill)
Sign up to request clarification or add additional context in comments.

Comments

1

Start with a pre-filled array:

var main = [
{ "id":"0", "value":500 },
{ "id":"3", "value":300 }
]

var fill = new Array(4).fill(0);


for (i = 0 ; i < main.length; i++){
    fill[main[i].id] = main[i].value
}

console.log(fill)

1 Comment

Thats works well man, but this "id" comes to me dynamically, there is a way to fill the final fill var with zero's?
1

If you want a solution that works even if you don't know the max size of the array you will fill, you can try adding this at the end:

fill.map(function (el) {
  return el === undefined ? 0 : el; 
});

Or in a ES6+ environment:

fill.map(el => el === undefined ? 0 : el);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.