javascript last element of array
// Method - 1 ([] operator)
const arr = [5, 3, 2, 7, 8];
const last = arr[arr.length - 1];
console.log(last);
/*
Output: 8
*/
// Method - 2 (Destructuring Assignment)
const arr = [5, 3, 2, 7, 8];
const [last] = arr.slice(-1);
console.log(last);
/*
Output: 8
*/
// Method - 3 (Array.prototype.pop())
const arr = [5, 3, 2, 7, 8];
const last = arr.slice(-1).pop();
console.log(last);
/*
Output: 8
*/
// Method - 4 (Underscore/Lodash Library)
const _ = require("underscore");
const arr = [5, 3, 2, 7, 8];
const last = _.last(arr);
console.log(last);
/*
Output: 8
*/var colors = ["red","blue","green"];
var green = colors[colors.length - 1];//get last item in the arrayarr.slice(-1)[0] let arr = [1,2,3]
arr[arr.length - 1] //returns last element in an arraylet arr = ['a', 'b', 'c']
arr.slice(-1)[0] // returns last element in an arrayvar last = arr.slice(-1)[0]
Also in JavaScript:
- outputstream to image js example
- chart.js line chart multiple labels
- how to export switch from react-router-dom
- jquery check if document loaded
- regular expression start and end with same character javascript
- Javascript append item to array
- allow cross origin node
- Generate random whole numbers within a range javascript
- jest tranform image
- Ocultar o mostrar elementos HTML con JQuery
- get top items from json object
- "scripts": { "start": "nodemon index.js", "test": "echo \"Error: no test specified\" && exit 1" },
- ng has unexpectedly closed (exit code 127).
- If 'ion-item' is an Angular component, then verify that it is part of this module.
- javascript remove all event listeners
- jquery check checkbox
- react native list view
- deparam javascript
- how to make a calculator websiteJS
- props react
- const userMessage Reaction = new UserMessage Reaction({ _id: mongoose.Types.ObjectId(), userId: "USERID", userName: "TESTUSERNAME", messageId: "TESTMESSAGEID", time: "TESTTIME" });
- react prevent back
- detect close tab javascript
- get form response with javascript