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?
{} 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.
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.
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.
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.
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);
Thay way:
const [head, ...rest] = myArray;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With