Rico Letterman Rico Letterman - 1 year ago 85
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)

// is outputing [3]. Expected is 1, 99, 3, 4

I'm using
as I see it as the most close method I can use to accomplish my goal. Also,
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 Source

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 )


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download