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

Time:12-21

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!

CodePudding user response:

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

CodePudding user response:

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).

CodePudding user response:

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

CodePudding user response:

This function should satisfy your conditions at basic level

// a - array, v - value to insert, i - position to insert 
const avi = (a, v, i) => { 
  r = a.slice(0, i); 
  r.push([a[i], v]);
  a.slice(i 1, a.length).forEach(e => r.push(e)); 
  return r;
}

console.log(JSON.stringify(avi([5,2,1,2], 8, 1)))
//=> "[5,[2,8],1,2]"
  • Related