Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to get first and last element of array in javascript

The rest parameter can only use at the end not anywhere else in the destructuring so it won't work as you expected.

Instead, you can destructor certain properties(an array is also an object in JS), for example, 0 for first and index of the last element for last.

let array = [1,2,3,4,5,6,7,8,9,0]

let {0 : a ,[array.length - 1] : b} = array;
console.log(a, b)
Expand snippet
Or its better way to extract length as an another variable and get last value based on that ( suggested by @Bergi) , it would work even there is no variable which refers the array.

let {0 : a ,length : l, [l - 1] : b} = [1,2,3,4,5,6,7,8,9,0];
console.log(a, b)
Comment

es6 get first and last element of array

let {0 : a ,length : l, [l - 1] : b} = [1,2,3,4,5,6,7,8,9,0];
console.log(a, b)
Comment

PREVIOUS NEXT
Code Example
Javascript :: extjs clone object 
Javascript :: reactjs wait for image to load from url 
Javascript :: if element in dict javascript 
Javascript :: javascript test if undefined 
Javascript :: How to find out what character key is pressed?#key#keyCode#code 
Javascript :: react native on refresh change color flat list 
Javascript :: Replace empty strings in object with null values 
Javascript :: synchronous file read 
Javascript :: separador de miles javascript 
Javascript :: search nested array in react javascript 
Javascript :: copying table element to clipboard using javascript 
Javascript :: javascript switch syntax 
Javascript :: grapesjs cdn 
Javascript :: handle multer error json 
Javascript :: VS Code Auto Import is bugging usestate 
Javascript :: react hook form submit outside form 
Javascript :: decrementar en java 
Javascript :: associative multidimensional array javascript 
Javascript :: Nextjs mongodb connection setup 
Javascript :: jest mock call 
Javascript :: js remove trailling lines 
Javascript :: vue router Async Scrolling 
Javascript :: detect javascript disabled 
Javascript :: date difference without weekends using moment js 
Javascript :: alert by code stackoverflow 
Javascript :: js !! 
Javascript :: remove the last character from a string in JavaScript, 
Javascript :: get date in milliseconds javascript 
Javascript :: javascript filter array return index 
Javascript :: sort array ij js 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =