T dhanunjay
T dhanunjay

Reputation: 820

How to splice multiple array elements and insert accordingly?

const data = response.data
console.log(data)
const temp = data.ssps_with_scated.splice(5, 1)(1, 3)[0]
data.ps_with_ed.splice(2, 1, 0, temp) 

i am trying to achieve finally i got it. But issue is, i cant expect the array value same all the time. So i have decided to re-arrange the array values based on the ID.

Upvotes: 2

Views: 2882

Answers (2)

munleashed
munleashed

Reputation: 1685

Well,

splice(7,1)(21,3)

This code will cause an error. Since Array.prototpy.slice returns a new array.
It would be the same if you would do this:

const a = [1,2,3]
const b = a.splice(1,1);
b(2,1) // b.splice(...) is not a function

EDITED: Maybe there is a faster/better solution but... You can make it more general but for your case only:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
const first = array[7];
const second = array[21];

// Add elements on certain indices in array (second and third)
array.splice(2, 0, first, second)

// Remove first from the array (index is 7 + 2 because we added 2 elements)
array.splice(9, 1)

// Remove 21 from the array (index is 22 - 1 because we added 2 elements and removed 1, not: number 21 is on index 22)
array.splice(21, 1);

Upvotes: 1

mars
mars

Reputation: 155

data shouldn't be a const since the value is getting updated. Splice can also only be called on one array at a time. If you need to call it on multiple arrays, create a loop or iterate over them.

If you want to inject the current value of the 7th position into the 2nd position... you'd need to do something like...

array.splice(2, 0, array[7])

Upvotes: 0

Related Questions