9
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.

Brombomb
  • 6,988
  • 4
  • 38
  • 57
  • what i want is , i want to have the provious values and if its the last value i want that also so basically i assume if and else withinn return NewdateData[k]; –  May 02 '11 at 11:46

6 Answers6

16

You can get the last value of an array with:

NewdateData[NewdateData.length-1];
Headshota
  • 21,021
  • 11
  • 61
  • 82
1

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      
JKhan
  • 1,157
  • 4
  • 14
  • 23
radman
  • 17,675
  • 11
  • 42
  • 58
1

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

1

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"))
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Anas
  • 1,000
  • 11
  • 18
0

Now we are living with ES6 features

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

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

console.log(a)

Abhishek
  • 164
  • 1
  • 2
  • 10
0

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)
akshit jain
  • 1
  • 1
  • 1