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.


Solution 1:

You can use:

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

Or in ES6:

const [head, ...tail] = arr;

Solution 2:

I would do using ES6 as below

const head = ([h]) => h;
const tail = ([, ...t]) => t;

const arr = [1,2,3,4,5];

alert(head(arr));

Solution 3:

The accepted answer is good, but for a more functional approach:

Heads

I'd use find, which returns the first element that returns a true-thy value in its predicate.

If you are sure your values are true-thy, you can write it as follows:

arr.find(Boolean)

If you want the first value, regardless of its value, you can write it as follows:

arr.find(_ => true)

Tails

Just as the others state, use slice

arr.slice(1);

Solution 4:

One can use lodash plugin which comes with Array Manipulating Features. Some of javascript functions operation given below without mutating the original array.

var originalArray = ["Banana", "Orange", "Apple", "Mango"];

//Equivalent of Unshift
let unshiftedArray = _.concat(["Lemon", "Pineapple"],originalArray);
console.log("unshiftedArray",unshiftedArray);

//Equivalent of shift
let shiftedArray = _.tail(originalArray);;
console.log("shiftedArray",shiftedArray);

//Equivalent of push
let pushedArray = _.concat(originalArray,'Lemon');
console.log("pushedArray",pushedArray);

//Equivalent of push
let poppedArray = _.dropRight(originalArray);
console.log("poppedArray",poppedArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>