0

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 ?

1
  • 1
    What is your expected result for the second and third examples you've given? Or when you have [...[null,null,null, null], ...[1,2]]? Commented Apr 21, 2020 at 7:45

2 Answers 2

1

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]

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

Comments

0

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 ]

Comments

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.