Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript head and tail on array without mutation

I found about JavaScript array operations Unshift, shift, push, pop

However all these operations mutate the array.

Is there a way I could use these functions without causing mutation on the original data?

Somehow I feel that reading the data should not cause mutation.

like image 856
Knows Not Much Avatar asked Feb 12 '16 11:02

Knows Not Much


People also ask

How do you splice an array without mutation?

Steps : Create the clone of the array using the spread operator or slice method. apply the splice method on the cloned array and return the extracted array.

Is array push a mutation?

Consider a common array mutation: push() . The push() method changes the original array by adding an item to the end. When you add an item, you're mutating the original array.

What is array mutation in JavaScript?

Array Mutations in JavaScript. Arrays in JavaScript are just objects, which means they can be mutated. In fact, many of the built-in array methods will mutate the array itself. This can mean the golden rule from above gets broken, just by using one of the built-in methods.


1 Answers

You can use:

var head = arr[0]; var tail = arr.slice(1); 

Or in ES6:

const [head, ...tail] = arr; 
like image 151
Davin Tryon Avatar answered Sep 30 '22 09:09

Davin Tryon