Getting the last value of an Array and showing it under X axis

21k views Asked by At
var NewdateData[] = [1,2,3,4,5,6,7,8,9,1,2,1,23,45,56]

This NewdateData is dynamically filled from database depending upon the selection made from the user interface.

I am using this NewdateData for displaying under the X axis Charts.

The issue I am facing is that, the values are not taken till the end , I want to have the last value to have under the X axis Labels.

xaxis: {tickFormatter: function(n)
{
    var k = Math.round(n);
    return NewdateData[k]; 
}

I am using flotr.

6

There are 6 answers

0
Anas On

Just do it with the map function.

this is the array what I want to pick the last item from it:-

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

loop over the array using map function to use the index parameter and compare it with animals array length:-

animals.map((animal, index) => animals.length -1 === index ? console.log("last item selected :)" + animal) : console.log("i'm not the last item"))
2
radman On

Very late to the party, but for posterity: in ES2015/ES6 you can use Array.prototype.slice. Doesn't mutate the array and a negative number gives you elements from the end of the array as a new array.

So to get the last element:

let arr = [1, 2, 3, 4, 5];
let last = arr.slice(-1); // last = 5      
3
Headshota On

You can get the last value of an array with:

NewdateData[NewdateData.length-1];
0
Shawn Swanson On

I don’t have enough points to comment on Radman’s post., but his solution is wrong.

let arr = [1, 2, 3, 4, 5]; let last = arr.slice(-1); // last = 5

Returns [5], not 5.

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

The correct answer:

let arr = [1, 2, 3, 4, 5];
let last = arr.slice(-1)[0];

References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

0
akshit jain On

A simple and convenient way is to use Array.prototype.at()

function returnLast(arr) {
  return arr.at(-1);
}

const cart = ['apple', 'banana', 'pear'];
const lastItem = returnLast(cart);

console.log(lastItem)  //pear

or just

const lastItem = cart.at(-1)
0
Abhishek On

Now we are living with ES6 features

var arr = [1,2,3,4,5,6]

const [a, ...b] = arr.reverse();

console.log(a)