Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
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:

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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; }

about 4 years ago · Juan Pablo Isaza Report

0

There are several different ways to do this, but you can reassign the current array index to an array like so:

Arr[1] = [Arr[1], 8]. Then if you wanted to continue adding to the array at index 1 in Arr, you could do something like Arr[1].push(x).

about 4 years ago · Juan Pablo Isaza Report

0

You could do something like this (Probably not the best answer, but may be helpful)

const addIntoArray = (arr, toAdd, index) => {
  arr[index] = typeof arr[index] == "number" ? [arr[index], toAdd] : [...arr[index], toAdd];
  return arr
}

Arr = [5,2,1,2]

console.log(Arr); // [ 5, 2, 1, 2 ]
addIntoArray(Arr, 1, 1)
console.log(Arr); // [ 5, [ 2, 1 ], 1, 2 ]
addIntoArray(Arr, 3, 1)
console.log(Arr) // [ 5, [ 2, 1, 3 ], 1, 2 ]

Basically ...arr expands the array and then we add toAdd at it's end and [arr[index], toAdd] creates an array with the first element as the number and the second the new element. (It modifies the original array, as shown in the example, so pay attention as it may lead to bugs)

The typeof arr[index] == "number"is just a simple/generic typecheck to see if there isn't an array already

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!