4

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
  • means, you just want to split the array? Commented Jun 8, 2020 at 15:46
  • 1
    You can slice it. But i don't think that it's possible with just destructuring. Commented Jun 8, 2020 at 15:48

2 Answers 2

2
rest = arr1.slice()
arr2 = rest.splice(0, range)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.