Reputation: 1526
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!
Upvotes: 0
Views: 200
Reputation:
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)
Upvotes: 1
Reputation: 10384
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);
Upvotes: 1
Reputation: 136094
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)
Upvotes: 1