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 :: filter an array of objects and match its key with values inside another array 
Javascript :: express js delete request 
Javascript :: timeline javascript 
Javascript :: jsdoc for express routes 
Javascript :: Disabling right click using Javascript 
Javascript :: js check if string is int 
Javascript :: path.join nodejs 
Javascript :: how to find smallest number in array js 
Javascript :: react native "modalize" above bottom navigation 
Javascript :: short if statements in javascript 
Javascript :: how to clone an object 
Javascript :: make country flags in js 
Javascript :: react lottie 
Javascript :: node-fetch 
Javascript :: javascript NEGATIVE_INFINITY 
Javascript :: The document.getElementById() Method 
Javascript :: magento 2 translate js 
Javascript :: how to find the particular key and value in json in javascript 
Javascript :: javascript onclick append a new row to table 
Javascript :: how to print a pdf 
Javascript :: Uncaught TypeError: $(...).jstree is not a function 
Javascript :: javascript declare string in multiple lines 
Javascript :: javascript foreach break 
Javascript :: p5js click on button 
Javascript :: body-parser vs express.json 
Javascript :: init select2 jquery 
Javascript :: index of an element 
Javascript :: javscript match word in string 
Javascript :: js find duplicates in array 
Javascript :: arrow functions in es6 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =