Destructuring Array in ReactJS

Viewed 104

Is there any way that I'm missing do this operation using destructuring an array. My Array

const arr1 = [1,2,3,4,5,6,7,8,9,10]

and I have a variable rest, arr2 and range=5. And I want first range which is 5 elements from the array and rest of the elements in rest variable. The way I try it to be

[arr2,...rest] = arr1

In this case, arr2 will have output 1 and rest have the rest of the array. Is there any way I can have first 5 elements in arr2

2 Answers
rest = arr1.slice()
arr2 = rest.splice(0, range)

That's not practical but just for fun you can do that (don't use it in real code though)

const [arr2, rest] = [arr1.slice(0, range), arr1.slice(range)]

Related