1
Array=[3,4,5,6,7,6,7]
Temp=[1,2]

how to store the value of temp in the array's 5th and 6th index in JavaScript

Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36
Iman Saha
  • 11
  • 1

4 Answers4

0

Use the array.splice function arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

This in combination with ...array to insert the values of the array instead of the array itself

let Array=[3,4,5,6,7,6,7];
console.log(Array);

let Temp=[1,2]
Array.splice(5, 0, ...Temp);

console.log(Array);

Refering this article

Aalexander
  • 4,987
  • 3
  • 11
  • 34
0

splice not only deletes items. You can also use it to insert items into the array. To effectively "spread" temp, you need the spread operator:

array.splice(5, 0, ...temp);

Then you can reuse splice to delete the old items:

array.splice(7, 2);
0

You could use splice, but it would mutate your original array

For safer use, make the result in the whole new array without affecting the original one, here I suggest using slice

const array=[3,4,5,6,7,6,7]
const temp=[1,2]
const res = [array.slice(0, 5), temp, array.slice(5)].flat()

console.log(res)
hgb123
  • 13,869
  • 3
  • 20
  • 38
0

const arr = [3,4,5,6,7,6,7];
const temp = [1, 2];
const res = [...arr.slice(0, 5), ...temp, ...arr.slice(5)];
console.log(res);

You can destructure the first part from your array until index 5 and the rest like this, you don't need to use .flat() to flatten the array.

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26