Reputation: 2594
My goal is start with an array with null values than if an other array has entries replace accordingly just to do en example
const a = [...[null,null,null, null], ...[1,2,3,4]]
I want an array [1,2,3,4]
at start the second array could be also empty like
const a = [...[null,null,null, null], ...[]]
or
const a = [...[null,null,null, null], ...[1]]
and so on ....
const a = [null,null,null, null];
const b = [1,2,3];
const c = a.map((item,i)=> b[i] ? b[i] : a[i])
Is there a better way ?
Upvotes: 0
Views: 156
Reputation: 386560
You could take Object.assign
with an array as target and get the values updated which are at the same index/key.
This works with sparse arrays as well.
const a = [null, null, null, null];
const b = [1, 2, 3, , 5];
// creating new, rather than mutating
const c = Object.assign([], a, b);
console.log(c); // [1, 2, 3, null, 5]
Upvotes: 1
Reputation: 3116
Check it out. just a simple for loop. I use Number.isNaN to do the validation. You can use other validations if you need to validate other kind of values.
const a = [null,null,null, null];
const b = [1,2,3];
let c=[...a]
for (let i = 0; i < b.length; i++) {
if(!Number.isNaN(b[i])){
c[i]=b[i]
}
}
This is the output:
[ 1, 2, 3, null ]
Upvotes: 0