Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add array to another array with keeping the same amount of indices

I have array A and I am trying to concat it to array B while array B keeps the same amount of indices.

for example:

const array_A = [1, 2, 3, 4];
const array_B = [0, 0, 0, 0, 0, 0, 0];

the result should look like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const result = [1, 2, 3, 4, 0, 0, 0];

I tried this approach

const result = array_A.concat(array_B);
console.log(result);

but then I got array of 11 indices which I only want array of 7 indices.

[1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0];

>Solution :

You could map over the second array and check if the first array has a value at that index.

array_B.map((n, i) => array_A[i] ?? n)

If the value at an index can be null / undefined, then the ?? operator will ignore it and use the array_B value. In that case, you can check if array_A has that specific index using the in opeartor

array_B.map((n, i) => i in array_A ? array_A[i] : n)

Here’s a snippet:

const array_A = [1, 2, 3, 4],
      array_B = [0, 0, 0, 0, 0, 0, 0],
      output1 = array_B.map((n, i) => array_A[i] ?? n),
      output2 = array_B.map((n, i) => i in array_A ? array_A[i] : n)
      
console.log(...output1)
console.log(...output2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading