Rico Letterman Rico Letterman - 28 days ago 12
Javascript Question

Populate each null element with other Array elements

I'm facing a hard time understanding arrays. I have two of them, which I want to pick one and populate null elements with the other array elements. I currently have the below:

var arr1 = [1,2,3,4]
var arr2 = [null, 99, null, null]

arr2.map((item) => {
if (item == null) {
arr2 = arr1.splice(item, 1)
}
})

console.log(arr2)
// is outputing [3]. Expected is 1, 99, 3, 4


I'm using
splice
as I see it as the most close method I can use to accomplish my goal. Also,
.map
is used but not a requirement.

I'll happy visit any related/already answered question, but since English is not my main language, I couldn't find any related question.

Answer

Your code is going to call splice(null, 1) on arr1 and assign the result on top of the entire arr2 three times.

map is designed to allow you to go through each item in an array and provide a substitute for each item, but you need to use it correctly, like this:

var arr1 = [1,2,3,4]
var arr2 = [null, 99, null, null]

arr2 = arr2.map((item, i) => item === null ? arr1[i] : item )

console.log(arr2)