Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the head and rest of an array in JavaScript?

Tags:

javascript

I have an array and would like to get its head and the rest. How do I do this using a destructuring assignment? Is this even possible?

If the array has only two elements, it's pretty easy:

const [head, rest] = myArray;

But what if it contains more than two entries?

like image 251
Golo Roden Avatar asked Nov 18 '16 09:11

Golo Roden


People also ask

What is {} and [] in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

How do you pull an element out of an array?

Combining indexOf() and splice() Methods Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.

How do I find the first and last elements of an array?

The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.

How do you split an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

You can use spread syntax for that.

const [head, ...rest] = myArray; 

var myArray = [1, 2, 3, 4, 5, 6];

const [head, ...rest] = myArray;

console.log(head);
console.log(rest);
like image 179
Pranav C Balan Avatar answered Oct 11 '22 13:10

Pranav C Balan


Thay way:

const [head, ...rest] = myArray;
like image 24
user2693928 Avatar answered Oct 11 '22 13:10

user2693928