JavaScript head and tail on array without mutation
JavascriptArraysJavascript Problem Overview
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.
Javascript Solutions
Solution 1 - Javascript
You can use:
var head = arr[0];
var tail = arr.slice(1);
Or in ES6:
const [head, ...tail] = arr;
Solution 2 - Javascript
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 - Javascript
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 - Javascript
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>
Solution 5 - Javascript
You could use this method soon: .at(index)
var array = ["a", "b", "c", "d", "e"];
console.log(array.at(0)); //"a"
console.log(array.at(-1)); //"e"
Or you could use this method: .slice(index)[0]
var array = ["a", "b", "c", "d", "e"];
console.log(array.slice(0)[0]); //"a"
console.log(array.slice(-1))[0]; //"e"