javascript array get last n elements code example
Example 1: javascript get last element of array
var colors = ["red","blue","green"];
var green = colors[colors.length - 1];
Example 2: get last element of array javascript
const arr = [5, 3, 2, 7, 8];
const last = arr[arr.length - 1];
console.log(last);
const arr = [5, 3, 2, 7, 8];
const [last] = arr.slice(-1);
console.log(last);
const arr = [5, 3, 2, 7, 8];
const last = arr.slice(-1).pop();
console.log(last);
const _ = require("underscore");
const arr = [5, 3, 2, 7, 8];
const last = _.last(arr);
console.log(last);
Example 3: return last two values of array in javascript
arr.slice(Math.max(arr.length - 5, 1))
Example 4: js get last array element
const array = [1, 2, 3, 4]
const lastArrayElement = array[array.length - 1]
Example 5: return last two values of array in javascript
var arr1 = [0, 1, 2, 3, 4, 5, 6, 7],
arr2 = [0, 1, 2, 3];
document.body.innerHTML = 'ARRAY 1: ' + arr1.slice(1).slice(-5) + '<br/>ARRAY 2: ' + arr2.slice(1).slice(-5);