user3887366
user3887366

Reputation: 2594

js fill array than replace with value

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

Answers (2)

Nina Scholz
Nina Scholz

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

MING WU
MING WU

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

Related Questions