1

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.

4 Answers 4

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

Just avoid the splice, and take the value you need with a ternary operator:

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)

Comments

0

You are on the right track, but the callback in map is supposed to return the element to be used in the new array. Try this instead.

arr2 = arr2.map((value, index) =>
    value != null ? value : arr1[index]
});

Comments

0

If you know that arr1 and arr2 have same size you could do

for(var i=0;i<arr2.length;i++){
  arr2[i]= arr2[i] || arr1[i];
}

I am using the for loop because it's ideal if you're just beginning working with arrays in order to fully understand how they work. The || operator, also known as null-coalescing operator, returns the first truthy operand to the assignment.

1 Comment

This would probably produce an undesired result if arr2 contained any 0s.

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.