Reputation: 651
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.
Upvotes: 1
Views: 61
Reputation: 101662
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)
Upvotes: 1
Reputation: 5235
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.
Upvotes: 0
Reputation: 350167
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)
Upvotes: 1
Reputation: 1735
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]
});
Upvotes: 0