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

In Javascript how do I create a secondary array in a specific index?

How do I create a subarray from an existing array in Javascript?

For example;

Arr = [5,2,1,2]

Then I want to insert 8 in position 1 of Arr, but keep the original value 2. So arr can become:

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

Arr = [5,[2,8],1,2]

I tried using concat, which sort of did something but duplicates all values.

Bear in mind that this can grow e.g. Arr = [5,[2,8,3,4],1,[2,3]]

Thanks!

>Solution :

You could assign the concatinated values.

const
    addAt = (array, value, index) => array[index] = [].concat(array[index], value),
    array = [5, 2, 1, 2];

addAt(array, 8, 1);
console.log(array)

addAt(array, 3, 1);
console.log(array)
.as-console-wrapper { max-height: 100% !important; top: 0; }
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