Adarsh Pawar
Adarsh Pawar

Reputation: 738

Destructuring Array in ReactJS

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

Upvotes: 4

Views: 178

Answers (2)

Dmytro Biletskyi
Dmytro Biletskyi

Reputation: 1903

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

Upvotes: 1

Josh Lind
Josh Lind

Reputation: 126

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

Upvotes: 2

Related Questions