Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last element of an array with a split in Javascript

Tags:

javascript

I'm trying to get the last array item after doing a split on a string using javascript.

    var str ="Watch-The-Crap-456".split('-')[this.length];
    console.log(str);​​​ 
   // want it to console log 456, now it consoles WATCH which is in array[0]

I tried doing [this.length - 1] to get me the last array item, but it gives me undefined, I know some of you might say create another variable to store the array, but it's interesting to see if we can keeps things shorter.

like image 884
unknown Avatar asked Nov 16 '12 13:11

unknown


People also ask

How do you slice the last element in JavaScript?

slice(-1) will return a copy of the last element of the array, but leaves the original array unmodified. To remove the last n elements from an array, use arr. splice(-n) (note the "p" in "splice"). The return value will be a new array containing the removed elements.

How do you find the last element of an array of strings?

To get the last item without knowing beforehand how many items it contains, you can use the length property to determine it, and since the array count starts at 0, you can pick the last item by referencing the <array>. length - 1 item.

Does split return an array JavaScript?

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

Which method of the array remove and returns the last element?

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.


2 Answers

How about:

"Watch-The-Crap-456".split('-').pop(); // returns 456
like image 84
lostsource Avatar answered Oct 18 '22 12:10

lostsource


this is defined in the deference (or at least does not reference the array).

A naive way would be two lines:

var str ="Watch-The-Crap-456".split('-');
console.log(str[str.length - 1]);​​​

See it in action.

like image 28
Jason McCreary Avatar answered Oct 18 '22 11:10

Jason McCreary