Get the last item in an array
Here is my JavaScript code so far:
var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.
javascript arrays
add a comment |
Here is my JavaScript code so far:
var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.
javascript arrays
add a comment |
Here is my JavaScript code so far:
var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.
javascript arrays
Here is my JavaScript code so far:
var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.
javascript arrays
javascript arrays
edited Jun 28 '18 at 19:59
Lucas Prestes
147115
147115
asked Jul 9 '10 at 19:45
balexanderbalexander
5,189103657
5,189103657
add a comment |
add a comment |
39 Answers
39
active
oldest
votes
1 2
next
if(loc_array[loc_array.length-1] == 'index.html'){
//do something
}else{
//something else.
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase()
.
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
96
"work for people without JS" - I... I don't follow.
– corsiKa
Aug 22 '13 at 23:17
115
Some weird people actually disable javascript in their browsers. It's shocking I know.
– Aaron Harun
Aug 24 '13 at 11:13
96
Can we all just agree that if a user disables JavaScript they're pretty much screwed anyway? Don't sacrifice the design and efficiency of your app just to support bizarre unlikely scenarios.
– devios1
Mar 24 '16 at 16:57
14
Don't you think that 99.9% of "users" who has disabled JS are actually bots fetching data from your html? Or developers "testing" if your site works w/o JS?
– Lukas
Apr 21 '17 at 20:30
36
Can we all just agree that many web devs don't have manners and include all sort of unwanted bloat scripts like tracking and that this is one of the very valid reasons to disable JS on random untrusted websites entirely? It's not as unlikely as some people think. It is actually the sane way of acting, if you value privacy at all.
– Zelphir
Dec 20 '17 at 10:33
|
show 7 more comments
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined
if the array is empty.
4
This wins for conciseness, while not changing the input, like.pop()
does.
– Jörn Zaefferer
Jan 24 '13 at 16:51
9
This might be slightly less efficient, depending on how slice is written.slice()
creates a new array, in this case with just the last element, just to access the last element, so you will have some additional memory allocation (which takes a finite amount of time).
– Gone Coding
Jun 14 '13 at 13:44
1
@IngoBürk yes :) performance overhead will be minimal though. the intermediate array is just one element long. as long as you're not using calling this a million times you should be fine.
– kritzikratzi
Mar 23 '14 at 19:18
76
regard the speed concerns: @user1941782 made a micro benchmark. slice() can run ~10 million times per second on a new computer. using [len-1] is ~1000 times faster, but both are so fast that they likely won't be the limiting factor; so imho there's no need to feel bad for using slice().
– kritzikratzi
Apr 20 '14 at 14:38
36
nice for the time when you are doing something likewindows.location.pathname.split('/').slice(-1)[0]
avoiding the need for an intermediate variable just so you can calllen
on it, since javascript doesn't understand[-1]
as being the last element of the array like some languages do.
– Michael
May 29 '15 at 16:34
|
show 2 more comments
Use Array.pop:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array
191
This works but it removes the item from the array, which isn't what the OP asked for.
– Wolverine
Aug 16 '12 at 1:41
31
I like using this on throwaway lists that I don't want to store in a variable:var last = path.split('/').pop();
Glad this answer is here!
– Daniel Buckmaster
Jan 7 '14 at 5:38
6
The OP says 'and if so grab the third to last instead'. If you pop, what was the third to last is no longer the third to last. .pop() does indeed 'get' the last item. I wholeheartedly agree though that it would be good to mention in the answer itself that this approach modifies the array.
– jinglesthula
Jan 21 '14 at 18:15
add a comment |
A shorter version of what @chaiguy posted:
Array.prototype.last = function() {
return this[this.length - 1];
}
Reading the -1 index returns undefined
already.
EDIT:
These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.
export function last(array) {
return array[array.length - 1];
}
9
I'm calling itpeek
as analogue topop
, when using an array like as stack
– Tobia
Apr 28 '15 at 14:14
8
If it's not obvious how this is to be actually used, here's an example:var lastItem = [3,2,1,5].last();
. The value oflastItem
is5
.
– user128216
Dec 5 '15 at 2:23
3
This answer is correct and also pretty clean BUT(!!!) A rule of thumb using Javascript is thatDo NOT modify objects you Do NOT own
. It's dangerous because of many reasons, such as 1. Other developers working in your team could get confused as this method is not standard 2.with any update in libraries or even using a lower or higher ECMAScript version it could easily get LOST!
– Farzad YZ
Oct 13 '16 at 16:21
12
I like this solution very much, but -following @FarzadYZ comment- w3schools.com/js/js_object_prototypes.asp states: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
– j.c
Dec 16 '16 at 14:04
4
how does this break Array.forEach()? as I have tried and did not see anything broke...
– Félix Brunet
Dec 7 '17 at 19:17
|
show 7 more comments
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
http://jsperf.com/slice-vs-length-1-arr
14
var last = arr[arr.length - 1]
is the best answer in this thread in terms of overall performance
– DrewT
May 15 '14 at 6:43
The latter returns an array.
– Cees Timmerman
Jun 18 '14 at 8:20
4
arr.length-1
may be 150-200 times faster but when the slowest method's speed is already in millions of operations per second I don't think performance is the main concern in 99.99% of the cases (and even more when slice/pop lets you extract the last element of an array that isn't saved in a variable, for code beauty purposes)
– Charles P.
Feb 26 '16 at 11:12
1
Thearr.slice(-1)[0]
is not clear to non js familiar programmer. Thearr[arr.length - 1]
is much more clear and easy to 'guess' what programmer have in mind :)
– Kamil Kiełczewski
Jun 20 '17 at 9:40
arr[arr.length-1]
is the most clear and the fastest
– doom
Jan 16 '18 at 11:10
add a comment |
Here's how to get it with no effect on the original ARRAY
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
If you use pop(), it will modify your array
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
But you can use this so it has no effect on the original array:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element
6
you should do slice(-1).pop(), otherwise you copy the entire array (you really only need to copy the last element).
– kritzikratzi
May 29 '15 at 23:46
No need for thatpop()
then: just doarr.slice(-1)[0]
– Christophe Marois
Apr 12 '17 at 5:48
add a comment |
I'd rather use array.pop()
than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
3
It's a bit slow, but you could doloc_array.slice().pop()
.
– Salehen Rahman
Jul 2 '13 at 18:28
13
@skizeey then better do loc_array.slice(-1).pop(), that slices off only the last element.
– kritzikratzi
Jul 20 '13 at 0:23
add a comment |
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo
, as .pop()
would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0]
solution.
You can also use the array destructuring to make it more ES6 ;) stackoverflow.com/a/46485581/31671
– alex
Oct 4 '17 at 7:52
12
Note that this solution performs a copy of the entire array.
– Brendan Annable
Jul 3 '18 at 1:56
It's just as unreadable as.slice(-1)[0]
but it's slower. Might as well use.slice
– bfred.it
Sep 19 '18 at 4:30
Copying the whole array just for "clean" syntax seems silly to me. It doesnt even look that nice
– Jemar Jones
Dec 13 '18 at 15:55
add a comment |
Getting the last item of an array can be achieved by using the slice method with negative values.
You can read more about it here at the bottom.
var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
//your code...
}
Using pop() will change your array, which is not always a good idea.
1
Slice returns an array, though, so usearr.slice(-1)[0]
, like this answer.
– Cees Timmerman
May 21 '13 at 10:31
@Cees Timmerman - Thanks. Iv'e fixed the code
– Mohoch
May 22 '13 at 6:57
3
If performance is an issue, know that this method is a lot slower thanarray[array.length - 1]
jsperf.com/get-last-item-from-array/13
– Bruno Peres
Mar 8 '17 at 2:54
add a comment |
You can use this pattern...
let [last] = arr.slice(-1);
While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.
add a comment |
If one wants to get the last element in one go, he/she may use Array#splice()
:
lastElement = document.location.href.split('/').splice(-1,1);
Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of splice(-1,1)
as a pop()
function that pops the last element.
3
Doesn't this return the last element in an array, instead of the last element itself?
– user663031
Dec 29 '12 at 7:02
2
@tozazaburo isn't that the same thing?
– Aram Kocharyan
Dec 29 '12 at 15:34
4
this modifies the array. you could use slice(-1) instead of splice(-1) to leave the original array untouched. @AramKocharyan no its not, compare["hi"]
vs"hi"
.
– kritzikratzi
Jul 20 '13 at 0:29
add a comment |
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $().get(-1)
undefined
16
But only if you already use jQuery anyway. Loading an entire library to do something every language supporting arrays can do natively is crazy.
– Ingo Bürk
Aug 24 '13 at 12:08
3
Negative slicing is not native in many old languages, and jQuery saves a lot of time in most cases, so this could be a good excuse to start using it.
– Cees Timmerman
Aug 27 '13 at 23:57
2
If you don't trust the language itself, using jQuery is a lie that you're telling yourself. This is literally nothing more than accessing an array element. There are many use-cases where I'd agree with you, but this is just too basic. Again, if you do already use jQuery in your project, it's completely fine. It's just not worth adding an entire, powerful library for something as trivial as accessing the last element of an array.
– Ingo Bürk
Aug 28 '13 at 12:25
2
Addition: If jQuery had a method$.defineVar = function (scope, name, value) { scope[name] = value; }
, I'd still usevar foo = 'bar'
instead of$.defineVar(window, 'foo', 'bar');
, no matter how much documentation jQuery throws at it. Besides, jQuery is well-documented, but so is Javascript. In fact, it's even specified. You really can't get more detailed than that.
– Ingo Bürk
Aug 28 '13 at 12:28
1
I just pointed out a reason. jQuery already avoided that pitfall.
– Cees Timmerman
Aug 28 '13 at 14:12
|
show 7 more comments
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
Object.defineProperty( Array.prototype, "getLast", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[ this.length - 1 ];
}
} );
There is no reason to assume that variable "undefined" is undefined. Anyone could write something like "var undefined = true;", breaking your code. And, by extending Array, you cause for..in loop to produce unexpected results. Good programmers know they have to check for..in loop for inherited values, but not everyone is a good programmer and we shall not break their code, too.
– Richard
Jul 26 '13 at 11:03
4
It would hardly break my code! Why do you think that? If someone wants to redefine undefined, then let them, though it's a pretty crazy thing to do. That's the power of JavaScript. They can also redefine Array.getLast if they like. Also, good programmers use Object.defineProperty to get around enumeration.
– devios1
Jul 26 '13 at 15:25
Updated answer to demo use ofObject.defineProperty
and also slimmed the function body as per @AramKocharyan.
– devios1
Jul 26 '13 at 17:54
add a comment |
I think if you only want get the element without remove, is more simple use this:
arr.slice(-1)
by the way... i didnt check performance, but i think is more simple and clean to write
add a comment |
I generally use underscorejs, with it you can just do
if (_.last(loc_array) === 'index.html'){
etc...
}
For me that is more semantic than loc_array.slice(-1)[0]
2
_.last
works with Lodash too.
– Rory O'Kane
Sep 6 '17 at 17:20
add a comment |
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop()
.
arr.pop()
is exactly as efficient as arr[arr.length-1]
, and both are the same speed as arr.push()
.
Therefore, you can get away with:
let thePop = arr.pop()
arr.push(thePop)
Which can be reduced to this (same speed):
arr.push(thePop = arr.pop())
This is twice as slow as arr[arr.length-1]
, but you don't have to stuff around with an index. That's worth gold on any day.
Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]
:
[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
arr[arr.length - 1] ------> 1 -----> 1
let myPop = arr.pop()
arr.push(myPop) ------> 2 -----> 2
arr.slice(-1).pop() ------> 36 -----> 924
arr.slice(-1)[0] ------> 36 -----> 924
[...arr].pop() ------> 120 -----> ~21,000,000 :)
The last three options, ESPECIALLY [...arr].pop()
, get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop()
probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.
Brilliant answer. Exactly what I needed when working withString.split()
– mklbtz
Oct 11 '18 at 14:46
1
If initial array can be empty, this approach will result incorrectly andwill be turned into
[undefined]
. You need to protect backward push with explicitundefined
check, something likemyPop !== undefined && arr.push(myPop)
– dhilt
Feb 6 at 8:36
add a comment |
Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.
var array = [[1,2,3], [4,5,6], [7,8,9]]
array.slice(-1)[0]
//instead of
array[array.length-1]
//Much easier to read with nested arrays
array.slice(-1)[0].slice(-1)[0]
//instead of
array[array.length-1][array[array.length-1].length-1]
Easier is a point of view, and I wont disagree, but creating a new instance of array only to fetch some item is surely not smart.
– Guilherme Ferreira
Feb 14 '17 at 20:24
add a comment |
You can add a last()
function to the Array
prototype.
Array.prototype.last = function () {
return this[this.length - 1];
};
6
Remember this is a highly discouraged anti-pattern though.
– caesarsol
Mar 6 '17 at 14:43
1
@caesarsol could you please explain why or provide a link regarding this?
– eko24ive
Oct 17 '17 at 8:10
2
@eko24ive In short, you are modifying global objects which are used both in your code and in any other library present in the scripts, and that is dangerous. Moreover, you expose your code to possible breakage in case of future language additions. Some libraries in the past did it, with big regret. Have a look at this for more: stackoverflow.com/questions/14034180/…
– caesarsol
Oct 24 '17 at 8:51
See my solution later on this page. Solution is to create a wrapper function name it "w()" that returns an object which has method last() which returns the last item of the array given as argument to w(). Then the result of w() in terms of the method last() behaves like arrays would if their prototype was given this method. But it is not so you are not breaking any global functionality. Remember JavaScript is prototype-based meaning every object can have its own methods, no need to mess up the prototype if all you need is a single new method.
– Panu Logic
Jun 28 '18 at 17:56
add a comment |
You could add a new property getter to the prototype of Array
so that it is accessible through all instances of Array
.
Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]
).
Finally you wrap it in a condition that checks whether the last
-property is still undefined
(not defined by another script that might rely on it).
if(typeof Array.prototype.last === 'undefined') {
Object.defineProperty(Array.prototype, 'last', {
get : function() {
return this[this.length - 1];
}
});
}
// Now you can access it like
[1, 2, 3].last; // => 3
// or
var test = [50, 1000];
alert(test.last); // Says '1000'
Does not work in IE ≤ 8.
Array.prototype.last
is alwaysundefined
? The if isn't working under Chrome 36
– bryc
Aug 23 '14 at 16:43
for me this is the best answer. Waaaay far the best
– Soldeplata Saketos
Jul 3 '18 at 9:19
add a comment |
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).
It is the best solution in terms of performance. But it is not the best in terms of code-quality. It is way too easy to type: var lastElement = arr[arr.lenght - 1];
– Panu Logic
Jun 28 '18 at 17:59
add a comment |
EDITED:
Recently I came up with one more solution which I now think is the best for my needs:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
With the above definition in effect I can now say:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
The name "w" stands for "wrapper".
You can see how you could easily add more
methods besides 'last()' to this wrapper.
I say "best for my needs", because this allows
me to easily add other such "helper methods"
to any JavaScript built-in type. What comes
to mind are the car() and cdr() of Lisp for
instance.
and a 4th one for fun and very readable :myArray.reverse()[0]
– mickro
Jun 27 '18 at 14:48
Why use a wrapper? If you have to call aw
function just make the function return the last item.
– bfred.it
Sep 19 '18 at 4:32
add a comment |
I think the easiest and super inefficient way is:
var array = ['fenerbahce','arsenal','milan'];
var reversed_array = array.reverse(); //inverts array [milan,arsenal,fenerbahce]
console.log(reversed_array[0]) // result is "milan".
39
This solution takes O(n) more memory and takes O(n) time. It's really not the ideal solution.
– hlin117
Jul 6 '15 at 18:09
10
This is highly inefficient. Don't do this.
– marton78
Jul 22 '15 at 12:17
2
Do not do this , it is just knowledge :)
– Osman Erdi
Mar 29 '16 at 23:56
2
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:27
But it sure is easy.
– Andy
May 4 '18 at 5:49
add a comment |
I'll suggest to create helper function and reuse it every time, you'll need it. Lets make function more general to be able to get not only last item, but also second from the last and so on.
function last(arr, i) {
var i = i || 0;
return arr[arr.length - (1 + i)];
}
Usage is simple
var arr = [1,2,3,4,5];
last(arr); //5
last(arr, 1); //4
last(arr, 9); //undefined
Now, lets solve the original issue
Grab second to last item form array. If the last item in the loc_array is "index.html" grab the third to last item instead.
Next line does the job
last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
So, you'll need to rewrite
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
in this way
var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === 'index.html' ? 2 : 1))));
or use additional variable to increase readability
var nodeName = last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));
See my answer which is very similar. Instead of creating a function "last()" I create function "w(theArray)" which returns an object which has the METHOD "last()" .
– Panu Logic
Jun 28 '18 at 17:49
add a comment |
In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.
Syntax:
arr.lastItem // get last item
arr.lastItem = 'value' // set last item
arr.lastIndex // get last index
You can use polyfill.
Proposal author: Keith Cirkel(chai autor)
add a comment |
The simple way to get last item of array:
var last_item = loc_array.reverse()[0];
Of course, we need to check to make sure array has at least one item first.
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– Vizllx
Nov 22 '18 at 3:30
The question is "How to get last item in an array", and my solution should works. :)
– Cong Nguyen
Nov 22 '18 at 3:56
1
this is the slowest way to get the last element... what if the array has a million elements?
– Deian
Dec 14 '18 at 19:07
add a comment |
Using lodash _.last(array) Gets the last element of array.
data = [1,2,3]
last = _.last(data)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
add a comment |
You can achieve this issue also without extracting an array from the url
This is my alternative
var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();
!Greetings¡
add a comment |
This can be done with lodash _.last
or _.nth
:
var data = [1, 2, 3, 4]
var last = _.nth(data, -1)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
add a comment |
Using ES6/ES2015 spread operator (...) you can do the following way.
const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)
Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.
9
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:26
@slang, agree. If you are doing hundreds to millions operations then you have to consider not to do it this way, but if you have to do it only several time than nobody will notice that. This example provides 'pure' call without changing actual data array.
– Vlad Bezden
Apr 16 '17 at 20:21
add a comment |
There is also a npm module, that add last
to Array.prototype
npm install array-prototype-last --save
usage
require('array-prototype-last');
[1, 2, 3].last; //=> 3
.last; //=> undefined
source of function?
– Matrix
Aug 1 '17 at 11:12
1
github.com/qialex/array-prototype-last/blob/master/index.js - it is here
– qiAlex
Aug 1 '17 at 13:34
it's simalar to this?Array.prototype.last = function(){ return this[this.length - 1]; }
+Object.defineProperty(Array.prototype, 'last', {enumerable: false});
– Matrix
Aug 1 '17 at 14:17
1
in your example last is function you should call it like ['a', 'b'].last() // 'b', while in module last is property and you can call it like ['a', 'b'].last // 'b'
– qiAlex
Aug 1 '17 at 15:11
1
yes, it is a function called each time
– qiAlex
Aug 1 '17 at 17:06
|
show 1 more comment
1 2
next
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: false,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3216013%2fget-the-last-item-in-an-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
StackExchange.ready(function () {
$("#show-editor-button input, #show-editor-button button").click(function () {
var showEditor = function() {
$("#show-editor-button").hide();
$("#post-form").removeClass("dno");
StackExchange.editor.finallyInit();
};
var useFancy = $(this).data('confirm-use-fancy');
if(useFancy == 'True') {
var popupTitle = $(this).data('confirm-fancy-title');
var popupBody = $(this).data('confirm-fancy-body');
var popupAccept = $(this).data('confirm-fancy-accept-button');
$(this).loadPopup({
url: '/post/self-answer-popup',
loaded: function(popup) {
var pTitle = $(popup).find('h2');
var pBody = $(popup).find('.popup-body');
var pSubmit = $(popup).find('.popup-submit');
pTitle.text(popupTitle);
pBody.html(popupBody);
pSubmit.val(popupAccept).click(showEditor);
}
})
} else{
var confirmText = $(this).data('confirm-text');
if (confirmText ? confirm(confirmText) : true) {
showEditor();
}
}
});
});
39 Answers
39
active
oldest
votes
39 Answers
39
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
if(loc_array[loc_array.length-1] == 'index.html'){
//do something
}else{
//something else.
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase()
.
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
96
"work for people without JS" - I... I don't follow.
– corsiKa
Aug 22 '13 at 23:17
115
Some weird people actually disable javascript in their browsers. It's shocking I know.
– Aaron Harun
Aug 24 '13 at 11:13
96
Can we all just agree that if a user disables JavaScript they're pretty much screwed anyway? Don't sacrifice the design and efficiency of your app just to support bizarre unlikely scenarios.
– devios1
Mar 24 '16 at 16:57
14
Don't you think that 99.9% of "users" who has disabled JS are actually bots fetching data from your html? Or developers "testing" if your site works w/o JS?
– Lukas
Apr 21 '17 at 20:30
36
Can we all just agree that many web devs don't have manners and include all sort of unwanted bloat scripts like tracking and that this is one of the very valid reasons to disable JS on random untrusted websites entirely? It's not as unlikely as some people think. It is actually the sane way of acting, if you value privacy at all.
– Zelphir
Dec 20 '17 at 10:33
|
show 7 more comments
if(loc_array[loc_array.length-1] == 'index.html'){
//do something
}else{
//something else.
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase()
.
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
96
"work for people without JS" - I... I don't follow.
– corsiKa
Aug 22 '13 at 23:17
115
Some weird people actually disable javascript in their browsers. It's shocking I know.
– Aaron Harun
Aug 24 '13 at 11:13
96
Can we all just agree that if a user disables JavaScript they're pretty much screwed anyway? Don't sacrifice the design and efficiency of your app just to support bizarre unlikely scenarios.
– devios1
Mar 24 '16 at 16:57
14
Don't you think that 99.9% of "users" who has disabled JS are actually bots fetching data from your html? Or developers "testing" if your site works w/o JS?
– Lukas
Apr 21 '17 at 20:30
36
Can we all just agree that many web devs don't have manners and include all sort of unwanted bloat scripts like tracking and that this is one of the very valid reasons to disable JS on random untrusted websites entirely? It's not as unlikely as some people think. It is actually the sane way of acting, if you value privacy at all.
– Zelphir
Dec 20 '17 at 10:33
|
show 7 more comments
if(loc_array[loc_array.length-1] == 'index.html'){
//do something
}else{
//something else.
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase()
.
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
if(loc_array[loc_array.length-1] == 'index.html'){
//do something
}else{
//something else.
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase()
.
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
edited Aug 24 '13 at 11:08
answered Jul 9 '10 at 19:48
Aaron HarunAaron Harun
16.4k73861
16.4k73861
96
"work for people without JS" - I... I don't follow.
– corsiKa
Aug 22 '13 at 23:17
115
Some weird people actually disable javascript in their browsers. It's shocking I know.
– Aaron Harun
Aug 24 '13 at 11:13
96
Can we all just agree that if a user disables JavaScript they're pretty much screwed anyway? Don't sacrifice the design and efficiency of your app just to support bizarre unlikely scenarios.
– devios1
Mar 24 '16 at 16:57
14
Don't you think that 99.9% of "users" who has disabled JS are actually bots fetching data from your html? Or developers "testing" if your site works w/o JS?
– Lukas
Apr 21 '17 at 20:30
36
Can we all just agree that many web devs don't have manners and include all sort of unwanted bloat scripts like tracking and that this is one of the very valid reasons to disable JS on random untrusted websites entirely? It's not as unlikely as some people think. It is actually the sane way of acting, if you value privacy at all.
– Zelphir
Dec 20 '17 at 10:33
|
show 7 more comments
96
"work for people without JS" - I... I don't follow.
– corsiKa
Aug 22 '13 at 23:17
115
Some weird people actually disable javascript in their browsers. It's shocking I know.
– Aaron Harun
Aug 24 '13 at 11:13
96
Can we all just agree that if a user disables JavaScript they're pretty much screwed anyway? Don't sacrifice the design and efficiency of your app just to support bizarre unlikely scenarios.
– devios1
Mar 24 '16 at 16:57
14
Don't you think that 99.9% of "users" who has disabled JS are actually bots fetching data from your html? Or developers "testing" if your site works w/o JS?
– Lukas
Apr 21 '17 at 20:30
36
Can we all just agree that many web devs don't have manners and include all sort of unwanted bloat scripts like tracking and that this is one of the very valid reasons to disable JS on random untrusted websites entirely? It's not as unlikely as some people think. It is actually the sane way of acting, if you value privacy at all.
– Zelphir
Dec 20 '17 at 10:33
96
96
"work for people without JS" - I... I don't follow.
– corsiKa
Aug 22 '13 at 23:17
"work for people without JS" - I... I don't follow.
– corsiKa
Aug 22 '13 at 23:17
115
115
Some weird people actually disable javascript in their browsers. It's shocking I know.
– Aaron Harun
Aug 24 '13 at 11:13
Some weird people actually disable javascript in their browsers. It's shocking I know.
– Aaron Harun
Aug 24 '13 at 11:13
96
96
Can we all just agree that if a user disables JavaScript they're pretty much screwed anyway? Don't sacrifice the design and efficiency of your app just to support bizarre unlikely scenarios.
– devios1
Mar 24 '16 at 16:57
Can we all just agree that if a user disables JavaScript they're pretty much screwed anyway? Don't sacrifice the design and efficiency of your app just to support bizarre unlikely scenarios.
– devios1
Mar 24 '16 at 16:57
14
14
Don't you think that 99.9% of "users" who has disabled JS are actually bots fetching data from your html? Or developers "testing" if your site works w/o JS?
– Lukas
Apr 21 '17 at 20:30
Don't you think that 99.9% of "users" who has disabled JS are actually bots fetching data from your html? Or developers "testing" if your site works w/o JS?
– Lukas
Apr 21 '17 at 20:30
36
36
Can we all just agree that many web devs don't have manners and include all sort of unwanted bloat scripts like tracking and that this is one of the very valid reasons to disable JS on random untrusted websites entirely? It's not as unlikely as some people think. It is actually the sane way of acting, if you value privacy at all.
– Zelphir
Dec 20 '17 at 10:33
Can we all just agree that many web devs don't have manners and include all sort of unwanted bloat scripts like tracking and that this is one of the very valid reasons to disable JS on random untrusted websites entirely? It's not as unlikely as some people think. It is actually the sane way of acting, if you value privacy at all.
– Zelphir
Dec 20 '17 at 10:33
|
show 7 more comments
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined
if the array is empty.
4
This wins for conciseness, while not changing the input, like.pop()
does.
– Jörn Zaefferer
Jan 24 '13 at 16:51
9
This might be slightly less efficient, depending on how slice is written.slice()
creates a new array, in this case with just the last element, just to access the last element, so you will have some additional memory allocation (which takes a finite amount of time).
– Gone Coding
Jun 14 '13 at 13:44
1
@IngoBürk yes :) performance overhead will be minimal though. the intermediate array is just one element long. as long as you're not using calling this a million times you should be fine.
– kritzikratzi
Mar 23 '14 at 19:18
76
regard the speed concerns: @user1941782 made a micro benchmark. slice() can run ~10 million times per second on a new computer. using [len-1] is ~1000 times faster, but both are so fast that they likely won't be the limiting factor; so imho there's no need to feel bad for using slice().
– kritzikratzi
Apr 20 '14 at 14:38
36
nice for the time when you are doing something likewindows.location.pathname.split('/').slice(-1)[0]
avoiding the need for an intermediate variable just so you can calllen
on it, since javascript doesn't understand[-1]
as being the last element of the array like some languages do.
– Michael
May 29 '15 at 16:34
|
show 2 more comments
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined
if the array is empty.
4
This wins for conciseness, while not changing the input, like.pop()
does.
– Jörn Zaefferer
Jan 24 '13 at 16:51
9
This might be slightly less efficient, depending on how slice is written.slice()
creates a new array, in this case with just the last element, just to access the last element, so you will have some additional memory allocation (which takes a finite amount of time).
– Gone Coding
Jun 14 '13 at 13:44
1
@IngoBürk yes :) performance overhead will be minimal though. the intermediate array is just one element long. as long as you're not using calling this a million times you should be fine.
– kritzikratzi
Mar 23 '14 at 19:18
76
regard the speed concerns: @user1941782 made a micro benchmark. slice() can run ~10 million times per second on a new computer. using [len-1] is ~1000 times faster, but both are so fast that they likely won't be the limiting factor; so imho there's no need to feel bad for using slice().
– kritzikratzi
Apr 20 '14 at 14:38
36
nice for the time when you are doing something likewindows.location.pathname.split('/').slice(-1)[0]
avoiding the need for an intermediate variable just so you can calllen
on it, since javascript doesn't understand[-1]
as being the last element of the array like some languages do.
– Michael
May 29 '15 at 16:34
|
show 2 more comments
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined
if the array is empty.
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined
if the array is empty.
edited May 16 '14 at 21:32
kuporific
6,45413041
6,45413041
answered Aug 23 '12 at 20:19
kritzikratzikritzikratzi
9,89512138
9,89512138
4
This wins for conciseness, while not changing the input, like.pop()
does.
– Jörn Zaefferer
Jan 24 '13 at 16:51
9
This might be slightly less efficient, depending on how slice is written.slice()
creates a new array, in this case with just the last element, just to access the last element, so you will have some additional memory allocation (which takes a finite amount of time).
– Gone Coding
Jun 14 '13 at 13:44
1
@IngoBürk yes :) performance overhead will be minimal though. the intermediate array is just one element long. as long as you're not using calling this a million times you should be fine.
– kritzikratzi
Mar 23 '14 at 19:18
76
regard the speed concerns: @user1941782 made a micro benchmark. slice() can run ~10 million times per second on a new computer. using [len-1] is ~1000 times faster, but both are so fast that they likely won't be the limiting factor; so imho there's no need to feel bad for using slice().
– kritzikratzi
Apr 20 '14 at 14:38
36
nice for the time when you are doing something likewindows.location.pathname.split('/').slice(-1)[0]
avoiding the need for an intermediate variable just so you can calllen
on it, since javascript doesn't understand[-1]
as being the last element of the array like some languages do.
– Michael
May 29 '15 at 16:34
|
show 2 more comments
4
This wins for conciseness, while not changing the input, like.pop()
does.
– Jörn Zaefferer
Jan 24 '13 at 16:51
9
This might be slightly less efficient, depending on how slice is written.slice()
creates a new array, in this case with just the last element, just to access the last element, so you will have some additional memory allocation (which takes a finite amount of time).
– Gone Coding
Jun 14 '13 at 13:44
1
@IngoBürk yes :) performance overhead will be minimal though. the intermediate array is just one element long. as long as you're not using calling this a million times you should be fine.
– kritzikratzi
Mar 23 '14 at 19:18
76
regard the speed concerns: @user1941782 made a micro benchmark. slice() can run ~10 million times per second on a new computer. using [len-1] is ~1000 times faster, but both are so fast that they likely won't be the limiting factor; so imho there's no need to feel bad for using slice().
– kritzikratzi
Apr 20 '14 at 14:38
36
nice for the time when you are doing something likewindows.location.pathname.split('/').slice(-1)[0]
avoiding the need for an intermediate variable just so you can calllen
on it, since javascript doesn't understand[-1]
as being the last element of the array like some languages do.
– Michael
May 29 '15 at 16:34
4
4
This wins for conciseness, while not changing the input, like
.pop()
does.– Jörn Zaefferer
Jan 24 '13 at 16:51
This wins for conciseness, while not changing the input, like
.pop()
does.– Jörn Zaefferer
Jan 24 '13 at 16:51
9
9
This might be slightly less efficient, depending on how slice is written.
slice()
creates a new array, in this case with just the last element, just to access the last element, so you will have some additional memory allocation (which takes a finite amount of time).– Gone Coding
Jun 14 '13 at 13:44
This might be slightly less efficient, depending on how slice is written.
slice()
creates a new array, in this case with just the last element, just to access the last element, so you will have some additional memory allocation (which takes a finite amount of time).– Gone Coding
Jun 14 '13 at 13:44
1
1
@IngoBürk yes :) performance overhead will be minimal though. the intermediate array is just one element long. as long as you're not using calling this a million times you should be fine.
– kritzikratzi
Mar 23 '14 at 19:18
@IngoBürk yes :) performance overhead will be minimal though. the intermediate array is just one element long. as long as you're not using calling this a million times you should be fine.
– kritzikratzi
Mar 23 '14 at 19:18
76
76
regard the speed concerns: @user1941782 made a micro benchmark. slice() can run ~10 million times per second on a new computer. using [len-1] is ~1000 times faster, but both are so fast that they likely won't be the limiting factor; so imho there's no need to feel bad for using slice().
– kritzikratzi
Apr 20 '14 at 14:38
regard the speed concerns: @user1941782 made a micro benchmark. slice() can run ~10 million times per second on a new computer. using [len-1] is ~1000 times faster, but both are so fast that they likely won't be the limiting factor; so imho there's no need to feel bad for using slice().
– kritzikratzi
Apr 20 '14 at 14:38
36
36
nice for the time when you are doing something like
windows.location.pathname.split('/').slice(-1)[0]
avoiding the need for an intermediate variable just so you can call len
on it, since javascript doesn't understand [-1]
as being the last element of the array like some languages do.– Michael
May 29 '15 at 16:34
nice for the time when you are doing something like
windows.location.pathname.split('/').slice(-1)[0]
avoiding the need for an intermediate variable just so you can call len
on it, since javascript doesn't understand [-1]
as being the last element of the array like some languages do.– Michael
May 29 '15 at 16:34
|
show 2 more comments
Use Array.pop:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array
191
This works but it removes the item from the array, which isn't what the OP asked for.
– Wolverine
Aug 16 '12 at 1:41
31
I like using this on throwaway lists that I don't want to store in a variable:var last = path.split('/').pop();
Glad this answer is here!
– Daniel Buckmaster
Jan 7 '14 at 5:38
6
The OP says 'and if so grab the third to last instead'. If you pop, what was the third to last is no longer the third to last. .pop() does indeed 'get' the last item. I wholeheartedly agree though that it would be good to mention in the answer itself that this approach modifies the array.
– jinglesthula
Jan 21 '14 at 18:15
add a comment |
Use Array.pop:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array
191
This works but it removes the item from the array, which isn't what the OP asked for.
– Wolverine
Aug 16 '12 at 1:41
31
I like using this on throwaway lists that I don't want to store in a variable:var last = path.split('/').pop();
Glad this answer is here!
– Daniel Buckmaster
Jan 7 '14 at 5:38
6
The OP says 'and if so grab the third to last instead'. If you pop, what was the third to last is no longer the third to last. .pop() does indeed 'get' the last item. I wholeheartedly agree though that it would be good to mention in the answer itself that this approach modifies the array.
– jinglesthula
Jan 21 '14 at 18:15
add a comment |
Use Array.pop:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array
Use Array.pop:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array
edited Sep 3 '14 at 21:31
Somatik
3,8203141
3,8203141
answered Jun 14 '12 at 14:06
mohawkemohawke
2,179182
2,179182
191
This works but it removes the item from the array, which isn't what the OP asked for.
– Wolverine
Aug 16 '12 at 1:41
31
I like using this on throwaway lists that I don't want to store in a variable:var last = path.split('/').pop();
Glad this answer is here!
– Daniel Buckmaster
Jan 7 '14 at 5:38
6
The OP says 'and if so grab the third to last instead'. If you pop, what was the third to last is no longer the third to last. .pop() does indeed 'get' the last item. I wholeheartedly agree though that it would be good to mention in the answer itself that this approach modifies the array.
– jinglesthula
Jan 21 '14 at 18:15
add a comment |
191
This works but it removes the item from the array, which isn't what the OP asked for.
– Wolverine
Aug 16 '12 at 1:41
31
I like using this on throwaway lists that I don't want to store in a variable:var last = path.split('/').pop();
Glad this answer is here!
– Daniel Buckmaster
Jan 7 '14 at 5:38
6
The OP says 'and if so grab the third to last instead'. If you pop, what was the third to last is no longer the third to last. .pop() does indeed 'get' the last item. I wholeheartedly agree though that it would be good to mention in the answer itself that this approach modifies the array.
– jinglesthula
Jan 21 '14 at 18:15
191
191
This works but it removes the item from the array, which isn't what the OP asked for.
– Wolverine
Aug 16 '12 at 1:41
This works but it removes the item from the array, which isn't what the OP asked for.
– Wolverine
Aug 16 '12 at 1:41
31
31
I like using this on throwaway lists that I don't want to store in a variable:
var last = path.split('/').pop();
Glad this answer is here!– Daniel Buckmaster
Jan 7 '14 at 5:38
I like using this on throwaway lists that I don't want to store in a variable:
var last = path.split('/').pop();
Glad this answer is here!– Daniel Buckmaster
Jan 7 '14 at 5:38
6
6
The OP says 'and if so grab the third to last instead'. If you pop, what was the third to last is no longer the third to last. .pop() does indeed 'get' the last item. I wholeheartedly agree though that it would be good to mention in the answer itself that this approach modifies the array.
– jinglesthula
Jan 21 '14 at 18:15
The OP says 'and if so grab the third to last instead'. If you pop, what was the third to last is no longer the third to last. .pop() does indeed 'get' the last item. I wholeheartedly agree though that it would be good to mention in the answer itself that this approach modifies the array.
– jinglesthula
Jan 21 '14 at 18:15
add a comment |
A shorter version of what @chaiguy posted:
Array.prototype.last = function() {
return this[this.length - 1];
}
Reading the -1 index returns undefined
already.
EDIT:
These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.
export function last(array) {
return array[array.length - 1];
}
9
I'm calling itpeek
as analogue topop
, when using an array like as stack
– Tobia
Apr 28 '15 at 14:14
8
If it's not obvious how this is to be actually used, here's an example:var lastItem = [3,2,1,5].last();
. The value oflastItem
is5
.
– user128216
Dec 5 '15 at 2:23
3
This answer is correct and also pretty clean BUT(!!!) A rule of thumb using Javascript is thatDo NOT modify objects you Do NOT own
. It's dangerous because of many reasons, such as 1. Other developers working in your team could get confused as this method is not standard 2.with any update in libraries or even using a lower or higher ECMAScript version it could easily get LOST!
– Farzad YZ
Oct 13 '16 at 16:21
12
I like this solution very much, but -following @FarzadYZ comment- w3schools.com/js/js_object_prototypes.asp states: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
– j.c
Dec 16 '16 at 14:04
4
how does this break Array.forEach()? as I have tried and did not see anything broke...
– Félix Brunet
Dec 7 '17 at 19:17
|
show 7 more comments
A shorter version of what @chaiguy posted:
Array.prototype.last = function() {
return this[this.length - 1];
}
Reading the -1 index returns undefined
already.
EDIT:
These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.
export function last(array) {
return array[array.length - 1];
}
9
I'm calling itpeek
as analogue topop
, when using an array like as stack
– Tobia
Apr 28 '15 at 14:14
8
If it's not obvious how this is to be actually used, here's an example:var lastItem = [3,2,1,5].last();
. The value oflastItem
is5
.
– user128216
Dec 5 '15 at 2:23
3
This answer is correct and also pretty clean BUT(!!!) A rule of thumb using Javascript is thatDo NOT modify objects you Do NOT own
. It's dangerous because of many reasons, such as 1. Other developers working in your team could get confused as this method is not standard 2.with any update in libraries or even using a lower or higher ECMAScript version it could easily get LOST!
– Farzad YZ
Oct 13 '16 at 16:21
12
I like this solution very much, but -following @FarzadYZ comment- w3schools.com/js/js_object_prototypes.asp states: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
– j.c
Dec 16 '16 at 14:04
4
how does this break Array.forEach()? as I have tried and did not see anything broke...
– Félix Brunet
Dec 7 '17 at 19:17
|
show 7 more comments
A shorter version of what @chaiguy posted:
Array.prototype.last = function() {
return this[this.length - 1];
}
Reading the -1 index returns undefined
already.
EDIT:
These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.
export function last(array) {
return array[array.length - 1];
}
A shorter version of what @chaiguy posted:
Array.prototype.last = function() {
return this[this.length - 1];
}
Reading the -1 index returns undefined
already.
EDIT:
These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.
export function last(array) {
return array[array.length - 1];
}
edited Sep 20 '18 at 16:24
answered Oct 1 '12 at 15:08
Aram KocharyanAram Kocharyan
16.2k106380
16.2k106380
9
I'm calling itpeek
as analogue topop
, when using an array like as stack
– Tobia
Apr 28 '15 at 14:14
8
If it's not obvious how this is to be actually used, here's an example:var lastItem = [3,2,1,5].last();
. The value oflastItem
is5
.
– user128216
Dec 5 '15 at 2:23
3
This answer is correct and also pretty clean BUT(!!!) A rule of thumb using Javascript is thatDo NOT modify objects you Do NOT own
. It's dangerous because of many reasons, such as 1. Other developers working in your team could get confused as this method is not standard 2.with any update in libraries or even using a lower or higher ECMAScript version it could easily get LOST!
– Farzad YZ
Oct 13 '16 at 16:21
12
I like this solution very much, but -following @FarzadYZ comment- w3schools.com/js/js_object_prototypes.asp states: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
– j.c
Dec 16 '16 at 14:04
4
how does this break Array.forEach()? as I have tried and did not see anything broke...
– Félix Brunet
Dec 7 '17 at 19:17
|
show 7 more comments
9
I'm calling itpeek
as analogue topop
, when using an array like as stack
– Tobia
Apr 28 '15 at 14:14
8
If it's not obvious how this is to be actually used, here's an example:var lastItem = [3,2,1,5].last();
. The value oflastItem
is5
.
– user128216
Dec 5 '15 at 2:23
3
This answer is correct and also pretty clean BUT(!!!) A rule of thumb using Javascript is thatDo NOT modify objects you Do NOT own
. It's dangerous because of many reasons, such as 1. Other developers working in your team could get confused as this method is not standard 2.with any update in libraries or even using a lower or higher ECMAScript version it could easily get LOST!
– Farzad YZ
Oct 13 '16 at 16:21
12
I like this solution very much, but -following @FarzadYZ comment- w3schools.com/js/js_object_prototypes.asp states: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
– j.c
Dec 16 '16 at 14:04
4
how does this break Array.forEach()? as I have tried and did not see anything broke...
– Félix Brunet
Dec 7 '17 at 19:17
9
9
I'm calling it
peek
as analogue to pop
, when using an array like as stack– Tobia
Apr 28 '15 at 14:14
I'm calling it
peek
as analogue to pop
, when using an array like as stack– Tobia
Apr 28 '15 at 14:14
8
8
If it's not obvious how this is to be actually used, here's an example:
var lastItem = [3,2,1,5].last();
. The value of lastItem
is 5
.– user128216
Dec 5 '15 at 2:23
If it's not obvious how this is to be actually used, here's an example:
var lastItem = [3,2,1,5].last();
. The value of lastItem
is 5
.– user128216
Dec 5 '15 at 2:23
3
3
This answer is correct and also pretty clean BUT(!!!) A rule of thumb using Javascript is that
Do NOT modify objects you Do NOT own
. It's dangerous because of many reasons, such as 1. Other developers working in your team could get confused as this method is not standard 2.with any update in libraries or even using a lower or higher ECMAScript version it could easily get LOST!– Farzad YZ
Oct 13 '16 at 16:21
This answer is correct and also pretty clean BUT(!!!) A rule of thumb using Javascript is that
Do NOT modify objects you Do NOT own
. It's dangerous because of many reasons, such as 1. Other developers working in your team could get confused as this method is not standard 2.with any update in libraries or even using a lower or higher ECMAScript version it could easily get LOST!– Farzad YZ
Oct 13 '16 at 16:21
12
12
I like this solution very much, but -following @FarzadYZ comment- w3schools.com/js/js_object_prototypes.asp states: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
– j.c
Dec 16 '16 at 14:04
I like this solution very much, but -following @FarzadYZ comment- w3schools.com/js/js_object_prototypes.asp states: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
– j.c
Dec 16 '16 at 14:04
4
4
how does this break Array.forEach()? as I have tried and did not see anything broke...
– Félix Brunet
Dec 7 '17 at 19:17
how does this break Array.forEach()? as I have tried and did not see anything broke...
– Félix Brunet
Dec 7 '17 at 19:17
|
show 7 more comments
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
http://jsperf.com/slice-vs-length-1-arr
14
var last = arr[arr.length - 1]
is the best answer in this thread in terms of overall performance
– DrewT
May 15 '14 at 6:43
The latter returns an array.
– Cees Timmerman
Jun 18 '14 at 8:20
4
arr.length-1
may be 150-200 times faster but when the slowest method's speed is already in millions of operations per second I don't think performance is the main concern in 99.99% of the cases (and even more when slice/pop lets you extract the last element of an array that isn't saved in a variable, for code beauty purposes)
– Charles P.
Feb 26 '16 at 11:12
1
Thearr.slice(-1)[0]
is not clear to non js familiar programmer. Thearr[arr.length - 1]
is much more clear and easy to 'guess' what programmer have in mind :)
– Kamil Kiełczewski
Jun 20 '17 at 9:40
arr[arr.length-1]
is the most clear and the fastest
– doom
Jan 16 '18 at 11:10
add a comment |
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
http://jsperf.com/slice-vs-length-1-arr
14
var last = arr[arr.length - 1]
is the best answer in this thread in terms of overall performance
– DrewT
May 15 '14 at 6:43
The latter returns an array.
– Cees Timmerman
Jun 18 '14 at 8:20
4
arr.length-1
may be 150-200 times faster but when the slowest method's speed is already in millions of operations per second I don't think performance is the main concern in 99.99% of the cases (and even more when slice/pop lets you extract the last element of an array that isn't saved in a variable, for code beauty purposes)
– Charles P.
Feb 26 '16 at 11:12
1
Thearr.slice(-1)[0]
is not clear to non js familiar programmer. Thearr[arr.length - 1]
is much more clear and easy to 'guess' what programmer have in mind :)
– Kamil Kiełczewski
Jun 20 '17 at 9:40
arr[arr.length-1]
is the most clear and the fastest
– doom
Jan 16 '18 at 11:10
add a comment |
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
http://jsperf.com/slice-vs-length-1-arr
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
http://jsperf.com/slice-vs-length-1-arr
edited Jun 18 '14 at 18:15
answered Jan 7 '14 at 21:57
Josh ClickJosh Click
1,1841010
1,1841010
14
var last = arr[arr.length - 1]
is the best answer in this thread in terms of overall performance
– DrewT
May 15 '14 at 6:43
The latter returns an array.
– Cees Timmerman
Jun 18 '14 at 8:20
4
arr.length-1
may be 150-200 times faster but when the slowest method's speed is already in millions of operations per second I don't think performance is the main concern in 99.99% of the cases (and even more when slice/pop lets you extract the last element of an array that isn't saved in a variable, for code beauty purposes)
– Charles P.
Feb 26 '16 at 11:12
1
Thearr.slice(-1)[0]
is not clear to non js familiar programmer. Thearr[arr.length - 1]
is much more clear and easy to 'guess' what programmer have in mind :)
– Kamil Kiełczewski
Jun 20 '17 at 9:40
arr[arr.length-1]
is the most clear and the fastest
– doom
Jan 16 '18 at 11:10
add a comment |
14
var last = arr[arr.length - 1]
is the best answer in this thread in terms of overall performance
– DrewT
May 15 '14 at 6:43
The latter returns an array.
– Cees Timmerman
Jun 18 '14 at 8:20
4
arr.length-1
may be 150-200 times faster but when the slowest method's speed is already in millions of operations per second I don't think performance is the main concern in 99.99% of the cases (and even more when slice/pop lets you extract the last element of an array that isn't saved in a variable, for code beauty purposes)
– Charles P.
Feb 26 '16 at 11:12
1
Thearr.slice(-1)[0]
is not clear to non js familiar programmer. Thearr[arr.length - 1]
is much more clear and easy to 'guess' what programmer have in mind :)
– Kamil Kiełczewski
Jun 20 '17 at 9:40
arr[arr.length-1]
is the most clear and the fastest
– doom
Jan 16 '18 at 11:10
14
14
var last = arr[arr.length - 1]
is the best answer in this thread in terms of overall performance– DrewT
May 15 '14 at 6:43
var last = arr[arr.length - 1]
is the best answer in this thread in terms of overall performance– DrewT
May 15 '14 at 6:43
The latter returns an array.
– Cees Timmerman
Jun 18 '14 at 8:20
The latter returns an array.
– Cees Timmerman
Jun 18 '14 at 8:20
4
4
arr.length-1
may be 150-200 times faster but when the slowest method's speed is already in millions of operations per second I don't think performance is the main concern in 99.99% of the cases (and even more when slice/pop lets you extract the last element of an array that isn't saved in a variable, for code beauty purposes)– Charles P.
Feb 26 '16 at 11:12
arr.length-1
may be 150-200 times faster but when the slowest method's speed is already in millions of operations per second I don't think performance is the main concern in 99.99% of the cases (and even more when slice/pop lets you extract the last element of an array that isn't saved in a variable, for code beauty purposes)– Charles P.
Feb 26 '16 at 11:12
1
1
The
arr.slice(-1)[0]
is not clear to non js familiar programmer. The arr[arr.length - 1]
is much more clear and easy to 'guess' what programmer have in mind :)– Kamil Kiełczewski
Jun 20 '17 at 9:40
The
arr.slice(-1)[0]
is not clear to non js familiar programmer. The arr[arr.length - 1]
is much more clear and easy to 'guess' what programmer have in mind :)– Kamil Kiełczewski
Jun 20 '17 at 9:40
arr[arr.length-1]
is the most clear and the fastest– doom
Jan 16 '18 at 11:10
arr[arr.length-1]
is the most clear and the fastest– doom
Jan 16 '18 at 11:10
add a comment |
Here's how to get it with no effect on the original ARRAY
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
If you use pop(), it will modify your array
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
But you can use this so it has no effect on the original array:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element
6
you should do slice(-1).pop(), otherwise you copy the entire array (you really only need to copy the last element).
– kritzikratzi
May 29 '15 at 23:46
No need for thatpop()
then: just doarr.slice(-1)[0]
– Christophe Marois
Apr 12 '17 at 5:48
add a comment |
Here's how to get it with no effect on the original ARRAY
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
If you use pop(), it will modify your array
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
But you can use this so it has no effect on the original array:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element
6
you should do slice(-1).pop(), otherwise you copy the entire array (you really only need to copy the last element).
– kritzikratzi
May 29 '15 at 23:46
No need for thatpop()
then: just doarr.slice(-1)[0]
– Christophe Marois
Apr 12 '17 at 5:48
add a comment |
Here's how to get it with no effect on the original ARRAY
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
If you use pop(), it will modify your array
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
But you can use this so it has no effect on the original array:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element
Here's how to get it with no effect on the original ARRAY
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
If you use pop(), it will modify your array
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
But you can use this so it has no effect on the original array:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element
edited Oct 24 '15 at 6:03
Carles Alcolea
3,12141336
3,12141336
answered Sep 3 '14 at 21:25
ucefkhucefkh
1,89311618
1,89311618
6
you should do slice(-1).pop(), otherwise you copy the entire array (you really only need to copy the last element).
– kritzikratzi
May 29 '15 at 23:46
No need for thatpop()
then: just doarr.slice(-1)[0]
– Christophe Marois
Apr 12 '17 at 5:48
add a comment |
6
you should do slice(-1).pop(), otherwise you copy the entire array (you really only need to copy the last element).
– kritzikratzi
May 29 '15 at 23:46
No need for thatpop()
then: just doarr.slice(-1)[0]
– Christophe Marois
Apr 12 '17 at 5:48
6
6
you should do slice(-1).pop(), otherwise you copy the entire array (you really only need to copy the last element).
– kritzikratzi
May 29 '15 at 23:46
you should do slice(-1).pop(), otherwise you copy the entire array (you really only need to copy the last element).
– kritzikratzi
May 29 '15 at 23:46
No need for that
pop()
then: just do arr.slice(-1)[0]
– Christophe Marois
Apr 12 '17 at 5:48
No need for that
pop()
then: just do arr.slice(-1)[0]
– Christophe Marois
Apr 12 '17 at 5:48
add a comment |
I'd rather use array.pop()
than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
3
It's a bit slow, but you could doloc_array.slice().pop()
.
– Salehen Rahman
Jul 2 '13 at 18:28
13
@skizeey then better do loc_array.slice(-1).pop(), that slices off only the last element.
– kritzikratzi
Jul 20 '13 at 0:23
add a comment |
I'd rather use array.pop()
than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
3
It's a bit slow, but you could doloc_array.slice().pop()
.
– Salehen Rahman
Jul 2 '13 at 18:28
13
@skizeey then better do loc_array.slice(-1).pop(), that slices off only the last element.
– kritzikratzi
Jul 20 '13 at 0:23
add a comment |
I'd rather use array.pop()
than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
I'd rather use array.pop()
than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
edited Oct 4 '17 at 7:53
alex
341k170768914
341k170768914
answered Feb 24 '12 at 18:39
Pablo MescherPablo Mescher
8,33262329
8,33262329
3
It's a bit slow, but you could doloc_array.slice().pop()
.
– Salehen Rahman
Jul 2 '13 at 18:28
13
@skizeey then better do loc_array.slice(-1).pop(), that slices off only the last element.
– kritzikratzi
Jul 20 '13 at 0:23
add a comment |
3
It's a bit slow, but you could doloc_array.slice().pop()
.
– Salehen Rahman
Jul 2 '13 at 18:28
13
@skizeey then better do loc_array.slice(-1).pop(), that slices off only the last element.
– kritzikratzi
Jul 20 '13 at 0:23
3
3
It's a bit slow, but you could do
loc_array.slice().pop()
.– Salehen Rahman
Jul 2 '13 at 18:28
It's a bit slow, but you could do
loc_array.slice().pop()
.– Salehen Rahman
Jul 2 '13 at 18:28
13
13
@skizeey then better do loc_array.slice(-1).pop(), that slices off only the last element.
– kritzikratzi
Jul 20 '13 at 0:23
@skizeey then better do loc_array.slice(-1).pop(), that slices off only the last element.
– kritzikratzi
Jul 20 '13 at 0:23
add a comment |
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo
, as .pop()
would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0]
solution.
You can also use the array destructuring to make it more ES6 ;) stackoverflow.com/a/46485581/31671
– alex
Oct 4 '17 at 7:52
12
Note that this solution performs a copy of the entire array.
– Brendan Annable
Jul 3 '18 at 1:56
It's just as unreadable as.slice(-1)[0]
but it's slower. Might as well use.slice
– bfred.it
Sep 19 '18 at 4:30
Copying the whole array just for "clean" syntax seems silly to me. It doesnt even look that nice
– Jemar Jones
Dec 13 '18 at 15:55
add a comment |
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo
, as .pop()
would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0]
solution.
You can also use the array destructuring to make it more ES6 ;) stackoverflow.com/a/46485581/31671
– alex
Oct 4 '17 at 7:52
12
Note that this solution performs a copy of the entire array.
– Brendan Annable
Jul 3 '18 at 1:56
It's just as unreadable as.slice(-1)[0]
but it's slower. Might as well use.slice
– bfred.it
Sep 19 '18 at 4:30
Copying the whole array just for "clean" syntax seems silly to me. It doesnt even look that nice
– Jemar Jones
Dec 13 '18 at 15:55
add a comment |
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo
, as .pop()
would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0]
solution.
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo
, as .pop()
would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0]
solution.
edited Oct 29 '18 at 9:56
Roko C. Buljan
127k21195225
127k21195225
answered Jun 16 '17 at 19:43
dddddd
45533
45533
You can also use the array destructuring to make it more ES6 ;) stackoverflow.com/a/46485581/31671
– alex
Oct 4 '17 at 7:52
12
Note that this solution performs a copy of the entire array.
– Brendan Annable
Jul 3 '18 at 1:56
It's just as unreadable as.slice(-1)[0]
but it's slower. Might as well use.slice
– bfred.it
Sep 19 '18 at 4:30
Copying the whole array just for "clean" syntax seems silly to me. It doesnt even look that nice
– Jemar Jones
Dec 13 '18 at 15:55
add a comment |
You can also use the array destructuring to make it more ES6 ;) stackoverflow.com/a/46485581/31671
– alex
Oct 4 '17 at 7:52
12
Note that this solution performs a copy of the entire array.
– Brendan Annable
Jul 3 '18 at 1:56
It's just as unreadable as.slice(-1)[0]
but it's slower. Might as well use.slice
– bfred.it
Sep 19 '18 at 4:30
Copying the whole array just for "clean" syntax seems silly to me. It doesnt even look that nice
– Jemar Jones
Dec 13 '18 at 15:55
You can also use the array destructuring to make it more ES6 ;) stackoverflow.com/a/46485581/31671
– alex
Oct 4 '17 at 7:52
You can also use the array destructuring to make it more ES6 ;) stackoverflow.com/a/46485581/31671
– alex
Oct 4 '17 at 7:52
12
12
Note that this solution performs a copy of the entire array.
– Brendan Annable
Jul 3 '18 at 1:56
Note that this solution performs a copy of the entire array.
– Brendan Annable
Jul 3 '18 at 1:56
It's just as unreadable as
.slice(-1)[0]
but it's slower. Might as well use .slice
– bfred.it
Sep 19 '18 at 4:30
It's just as unreadable as
.slice(-1)[0]
but it's slower. Might as well use .slice
– bfred.it
Sep 19 '18 at 4:30
Copying the whole array just for "clean" syntax seems silly to me. It doesnt even look that nice
– Jemar Jones
Dec 13 '18 at 15:55
Copying the whole array just for "clean" syntax seems silly to me. It doesnt even look that nice
– Jemar Jones
Dec 13 '18 at 15:55
add a comment |
Getting the last item of an array can be achieved by using the slice method with negative values.
You can read more about it here at the bottom.
var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
//your code...
}
Using pop() will change your array, which is not always a good idea.
1
Slice returns an array, though, so usearr.slice(-1)[0]
, like this answer.
– Cees Timmerman
May 21 '13 at 10:31
@Cees Timmerman - Thanks. Iv'e fixed the code
– Mohoch
May 22 '13 at 6:57
3
If performance is an issue, know that this method is a lot slower thanarray[array.length - 1]
jsperf.com/get-last-item-from-array/13
– Bruno Peres
Mar 8 '17 at 2:54
add a comment |
Getting the last item of an array can be achieved by using the slice method with negative values.
You can read more about it here at the bottom.
var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
//your code...
}
Using pop() will change your array, which is not always a good idea.
1
Slice returns an array, though, so usearr.slice(-1)[0]
, like this answer.
– Cees Timmerman
May 21 '13 at 10:31
@Cees Timmerman - Thanks. Iv'e fixed the code
– Mohoch
May 22 '13 at 6:57
3
If performance is an issue, know that this method is a lot slower thanarray[array.length - 1]
jsperf.com/get-last-item-from-array/13
– Bruno Peres
Mar 8 '17 at 2:54
add a comment |
Getting the last item of an array can be achieved by using the slice method with negative values.
You can read more about it here at the bottom.
var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
//your code...
}
Using pop() will change your array, which is not always a good idea.
Getting the last item of an array can be achieved by using the slice method with negative values.
You can read more about it here at the bottom.
var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
//your code...
}
Using pop() will change your array, which is not always a good idea.
edited Mar 31 '16 at 8:26
answered Feb 12 '13 at 9:13
MohochMohoch
1,55511823
1,55511823
1
Slice returns an array, though, so usearr.slice(-1)[0]
, like this answer.
– Cees Timmerman
May 21 '13 at 10:31
@Cees Timmerman - Thanks. Iv'e fixed the code
– Mohoch
May 22 '13 at 6:57
3
If performance is an issue, know that this method is a lot slower thanarray[array.length - 1]
jsperf.com/get-last-item-from-array/13
– Bruno Peres
Mar 8 '17 at 2:54
add a comment |
1
Slice returns an array, though, so usearr.slice(-1)[0]
, like this answer.
– Cees Timmerman
May 21 '13 at 10:31
@Cees Timmerman - Thanks. Iv'e fixed the code
– Mohoch
May 22 '13 at 6:57
3
If performance is an issue, know that this method is a lot slower thanarray[array.length - 1]
jsperf.com/get-last-item-from-array/13
– Bruno Peres
Mar 8 '17 at 2:54
1
1
Slice returns an array, though, so use
arr.slice(-1)[0]
, like this answer.– Cees Timmerman
May 21 '13 at 10:31
Slice returns an array, though, so use
arr.slice(-1)[0]
, like this answer.– Cees Timmerman
May 21 '13 at 10:31
@Cees Timmerman - Thanks. Iv'e fixed the code
– Mohoch
May 22 '13 at 6:57
@Cees Timmerman - Thanks. Iv'e fixed the code
– Mohoch
May 22 '13 at 6:57
3
3
If performance is an issue, know that this method is a lot slower than
array[array.length - 1]
jsperf.com/get-last-item-from-array/13– Bruno Peres
Mar 8 '17 at 2:54
If performance is an issue, know that this method is a lot slower than
array[array.length - 1]
jsperf.com/get-last-item-from-array/13– Bruno Peres
Mar 8 '17 at 2:54
add a comment |
You can use this pattern...
let [last] = arr.slice(-1);
While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.
add a comment |
You can use this pattern...
let [last] = arr.slice(-1);
While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.
add a comment |
You can use this pattern...
let [last] = arr.slice(-1);
While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.
You can use this pattern...
let [last] = arr.slice(-1);
While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.
answered Sep 29 '17 at 9:13
alexalex
341k170768914
341k170768914
add a comment |
add a comment |
If one wants to get the last element in one go, he/she may use Array#splice()
:
lastElement = document.location.href.split('/').splice(-1,1);
Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of splice(-1,1)
as a pop()
function that pops the last element.
3
Doesn't this return the last element in an array, instead of the last element itself?
– user663031
Dec 29 '12 at 7:02
2
@tozazaburo isn't that the same thing?
– Aram Kocharyan
Dec 29 '12 at 15:34
4
this modifies the array. you could use slice(-1) instead of splice(-1) to leave the original array untouched. @AramKocharyan no its not, compare["hi"]
vs"hi"
.
– kritzikratzi
Jul 20 '13 at 0:29
add a comment |
If one wants to get the last element in one go, he/she may use Array#splice()
:
lastElement = document.location.href.split('/').splice(-1,1);
Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of splice(-1,1)
as a pop()
function that pops the last element.
3
Doesn't this return the last element in an array, instead of the last element itself?
– user663031
Dec 29 '12 at 7:02
2
@tozazaburo isn't that the same thing?
– Aram Kocharyan
Dec 29 '12 at 15:34
4
this modifies the array. you could use slice(-1) instead of splice(-1) to leave the original array untouched. @AramKocharyan no its not, compare["hi"]
vs"hi"
.
– kritzikratzi
Jul 20 '13 at 0:29
add a comment |
If one wants to get the last element in one go, he/she may use Array#splice()
:
lastElement = document.location.href.split('/').splice(-1,1);
Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of splice(-1,1)
as a pop()
function that pops the last element.
If one wants to get the last element in one go, he/she may use Array#splice()
:
lastElement = document.location.href.split('/').splice(-1,1);
Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of splice(-1,1)
as a pop()
function that pops the last element.
edited Feb 14 '18 at 17:45
illright
2,50221534
2,50221534
answered Mar 16 '12 at 0:53
user1144616user1144616
5761815
5761815
3
Doesn't this return the last element in an array, instead of the last element itself?
– user663031
Dec 29 '12 at 7:02
2
@tozazaburo isn't that the same thing?
– Aram Kocharyan
Dec 29 '12 at 15:34
4
this modifies the array. you could use slice(-1) instead of splice(-1) to leave the original array untouched. @AramKocharyan no its not, compare["hi"]
vs"hi"
.
– kritzikratzi
Jul 20 '13 at 0:29
add a comment |
3
Doesn't this return the last element in an array, instead of the last element itself?
– user663031
Dec 29 '12 at 7:02
2
@tozazaburo isn't that the same thing?
– Aram Kocharyan
Dec 29 '12 at 15:34
4
this modifies the array. you could use slice(-1) instead of splice(-1) to leave the original array untouched. @AramKocharyan no its not, compare["hi"]
vs"hi"
.
– kritzikratzi
Jul 20 '13 at 0:29
3
3
Doesn't this return the last element in an array, instead of the last element itself?
– user663031
Dec 29 '12 at 7:02
Doesn't this return the last element in an array, instead of the last element itself?
– user663031
Dec 29 '12 at 7:02
2
2
@tozazaburo isn't that the same thing?
– Aram Kocharyan
Dec 29 '12 at 15:34
@tozazaburo isn't that the same thing?
– Aram Kocharyan
Dec 29 '12 at 15:34
4
4
this modifies the array. you could use slice(-1) instead of splice(-1) to leave the original array untouched. @AramKocharyan no its not, compare
["hi"]
vs "hi"
.– kritzikratzi
Jul 20 '13 at 0:29
this modifies the array. you could use slice(-1) instead of splice(-1) to leave the original array untouched. @AramKocharyan no its not, compare
["hi"]
vs "hi"
.– kritzikratzi
Jul 20 '13 at 0:29
add a comment |
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $().get(-1)
undefined
16
But only if you already use jQuery anyway. Loading an entire library to do something every language supporting arrays can do natively is crazy.
– Ingo Bürk
Aug 24 '13 at 12:08
3
Negative slicing is not native in many old languages, and jQuery saves a lot of time in most cases, so this could be a good excuse to start using it.
– Cees Timmerman
Aug 27 '13 at 23:57
2
If you don't trust the language itself, using jQuery is a lie that you're telling yourself. This is literally nothing more than accessing an array element. There are many use-cases where I'd agree with you, but this is just too basic. Again, if you do already use jQuery in your project, it's completely fine. It's just not worth adding an entire, powerful library for something as trivial as accessing the last element of an array.
– Ingo Bürk
Aug 28 '13 at 12:25
2
Addition: If jQuery had a method$.defineVar = function (scope, name, value) { scope[name] = value; }
, I'd still usevar foo = 'bar'
instead of$.defineVar(window, 'foo', 'bar');
, no matter how much documentation jQuery throws at it. Besides, jQuery is well-documented, but so is Javascript. In fact, it's even specified. You really can't get more detailed than that.
– Ingo Bürk
Aug 28 '13 at 12:28
1
I just pointed out a reason. jQuery already avoided that pitfall.
– Cees Timmerman
Aug 28 '13 at 14:12
|
show 7 more comments
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $().get(-1)
undefined
16
But only if you already use jQuery anyway. Loading an entire library to do something every language supporting arrays can do natively is crazy.
– Ingo Bürk
Aug 24 '13 at 12:08
3
Negative slicing is not native in many old languages, and jQuery saves a lot of time in most cases, so this could be a good excuse to start using it.
– Cees Timmerman
Aug 27 '13 at 23:57
2
If you don't trust the language itself, using jQuery is a lie that you're telling yourself. This is literally nothing more than accessing an array element. There are many use-cases where I'd agree with you, but this is just too basic. Again, if you do already use jQuery in your project, it's completely fine. It's just not worth adding an entire, powerful library for something as trivial as accessing the last element of an array.
– Ingo Bürk
Aug 28 '13 at 12:25
2
Addition: If jQuery had a method$.defineVar = function (scope, name, value) { scope[name] = value; }
, I'd still usevar foo = 'bar'
instead of$.defineVar(window, 'foo', 'bar');
, no matter how much documentation jQuery throws at it. Besides, jQuery is well-documented, but so is Javascript. In fact, it's even specified. You really can't get more detailed than that.
– Ingo Bürk
Aug 28 '13 at 12:28
1
I just pointed out a reason. jQuery already avoided that pitfall.
– Cees Timmerman
Aug 28 '13 at 14:12
|
show 7 more comments
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $().get(-1)
undefined
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $().get(-1)
undefined
answered May 21 '13 at 10:28
Cees TimmermanCees Timmerman
8,36735585
8,36735585
16
But only if you already use jQuery anyway. Loading an entire library to do something every language supporting arrays can do natively is crazy.
– Ingo Bürk
Aug 24 '13 at 12:08
3
Negative slicing is not native in many old languages, and jQuery saves a lot of time in most cases, so this could be a good excuse to start using it.
– Cees Timmerman
Aug 27 '13 at 23:57
2
If you don't trust the language itself, using jQuery is a lie that you're telling yourself. This is literally nothing more than accessing an array element. There are many use-cases where I'd agree with you, but this is just too basic. Again, if you do already use jQuery in your project, it's completely fine. It's just not worth adding an entire, powerful library for something as trivial as accessing the last element of an array.
– Ingo Bürk
Aug 28 '13 at 12:25
2
Addition: If jQuery had a method$.defineVar = function (scope, name, value) { scope[name] = value; }
, I'd still usevar foo = 'bar'
instead of$.defineVar(window, 'foo', 'bar');
, no matter how much documentation jQuery throws at it. Besides, jQuery is well-documented, but so is Javascript. In fact, it's even specified. You really can't get more detailed than that.
– Ingo Bürk
Aug 28 '13 at 12:28
1
I just pointed out a reason. jQuery already avoided that pitfall.
– Cees Timmerman
Aug 28 '13 at 14:12
|
show 7 more comments
16
But only if you already use jQuery anyway. Loading an entire library to do something every language supporting arrays can do natively is crazy.
– Ingo Bürk
Aug 24 '13 at 12:08
3
Negative slicing is not native in many old languages, and jQuery saves a lot of time in most cases, so this could be a good excuse to start using it.
– Cees Timmerman
Aug 27 '13 at 23:57
2
If you don't trust the language itself, using jQuery is a lie that you're telling yourself. This is literally nothing more than accessing an array element. There are many use-cases where I'd agree with you, but this is just too basic. Again, if you do already use jQuery in your project, it's completely fine. It's just not worth adding an entire, powerful library for something as trivial as accessing the last element of an array.
– Ingo Bürk
Aug 28 '13 at 12:25
2
Addition: If jQuery had a method$.defineVar = function (scope, name, value) { scope[name] = value; }
, I'd still usevar foo = 'bar'
instead of$.defineVar(window, 'foo', 'bar');
, no matter how much documentation jQuery throws at it. Besides, jQuery is well-documented, but so is Javascript. In fact, it's even specified. You really can't get more detailed than that.
– Ingo Bürk
Aug 28 '13 at 12:28
1
I just pointed out a reason. jQuery already avoided that pitfall.
– Cees Timmerman
Aug 28 '13 at 14:12
16
16
But only if you already use jQuery anyway. Loading an entire library to do something every language supporting arrays can do natively is crazy.
– Ingo Bürk
Aug 24 '13 at 12:08
But only if you already use jQuery anyway. Loading an entire library to do something every language supporting arrays can do natively is crazy.
– Ingo Bürk
Aug 24 '13 at 12:08
3
3
Negative slicing is not native in many old languages, and jQuery saves a lot of time in most cases, so this could be a good excuse to start using it.
– Cees Timmerman
Aug 27 '13 at 23:57
Negative slicing is not native in many old languages, and jQuery saves a lot of time in most cases, so this could be a good excuse to start using it.
– Cees Timmerman
Aug 27 '13 at 23:57
2
2
If you don't trust the language itself, using jQuery is a lie that you're telling yourself. This is literally nothing more than accessing an array element. There are many use-cases where I'd agree with you, but this is just too basic. Again, if you do already use jQuery in your project, it's completely fine. It's just not worth adding an entire, powerful library for something as trivial as accessing the last element of an array.
– Ingo Bürk
Aug 28 '13 at 12:25
If you don't trust the language itself, using jQuery is a lie that you're telling yourself. This is literally nothing more than accessing an array element. There are many use-cases where I'd agree with you, but this is just too basic. Again, if you do already use jQuery in your project, it's completely fine. It's just not worth adding an entire, powerful library for something as trivial as accessing the last element of an array.
– Ingo Bürk
Aug 28 '13 at 12:25
2
2
Addition: If jQuery had a method
$.defineVar = function (scope, name, value) { scope[name] = value; }
, I'd still use var foo = 'bar'
instead of $.defineVar(window, 'foo', 'bar');
, no matter how much documentation jQuery throws at it. Besides, jQuery is well-documented, but so is Javascript. In fact, it's even specified. You really can't get more detailed than that.– Ingo Bürk
Aug 28 '13 at 12:28
Addition: If jQuery had a method
$.defineVar = function (scope, name, value) { scope[name] = value; }
, I'd still use var foo = 'bar'
instead of $.defineVar(window, 'foo', 'bar');
, no matter how much documentation jQuery throws at it. Besides, jQuery is well-documented, but so is Javascript. In fact, it's even specified. You really can't get more detailed than that.– Ingo Bürk
Aug 28 '13 at 12:28
1
1
I just pointed out a reason. jQuery already avoided that pitfall.
– Cees Timmerman
Aug 28 '13 at 14:12
I just pointed out a reason. jQuery already avoided that pitfall.
– Cees Timmerman
Aug 28 '13 at 14:12
|
show 7 more comments
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
Object.defineProperty( Array.prototype, "getLast", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[ this.length - 1 ];
}
} );
There is no reason to assume that variable "undefined" is undefined. Anyone could write something like "var undefined = true;", breaking your code. And, by extending Array, you cause for..in loop to produce unexpected results. Good programmers know they have to check for..in loop for inherited values, but not everyone is a good programmer and we shall not break their code, too.
– Richard
Jul 26 '13 at 11:03
4
It would hardly break my code! Why do you think that? If someone wants to redefine undefined, then let them, though it's a pretty crazy thing to do. That's the power of JavaScript. They can also redefine Array.getLast if they like. Also, good programmers use Object.defineProperty to get around enumeration.
– devios1
Jul 26 '13 at 15:25
Updated answer to demo use ofObject.defineProperty
and also slimmed the function body as per @AramKocharyan.
– devios1
Jul 26 '13 at 17:54
add a comment |
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
Object.defineProperty( Array.prototype, "getLast", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[ this.length - 1 ];
}
} );
There is no reason to assume that variable "undefined" is undefined. Anyone could write something like "var undefined = true;", breaking your code. And, by extending Array, you cause for..in loop to produce unexpected results. Good programmers know they have to check for..in loop for inherited values, but not everyone is a good programmer and we shall not break their code, too.
– Richard
Jul 26 '13 at 11:03
4
It would hardly break my code! Why do you think that? If someone wants to redefine undefined, then let them, though it's a pretty crazy thing to do. That's the power of JavaScript. They can also redefine Array.getLast if they like. Also, good programmers use Object.defineProperty to get around enumeration.
– devios1
Jul 26 '13 at 15:25
Updated answer to demo use ofObject.defineProperty
and also slimmed the function body as per @AramKocharyan.
– devios1
Jul 26 '13 at 17:54
add a comment |
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
Object.defineProperty( Array.prototype, "getLast", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[ this.length - 1 ];
}
} );
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
Object.defineProperty( Array.prototype, "getLast", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[ this.length - 1 ];
}
} );
edited Jul 26 '13 at 17:52
answered Sep 2 '12 at 17:32
devios1devios1
19.5k35130217
19.5k35130217
There is no reason to assume that variable "undefined" is undefined. Anyone could write something like "var undefined = true;", breaking your code. And, by extending Array, you cause for..in loop to produce unexpected results. Good programmers know they have to check for..in loop for inherited values, but not everyone is a good programmer and we shall not break their code, too.
– Richard
Jul 26 '13 at 11:03
4
It would hardly break my code! Why do you think that? If someone wants to redefine undefined, then let them, though it's a pretty crazy thing to do. That's the power of JavaScript. They can also redefine Array.getLast if they like. Also, good programmers use Object.defineProperty to get around enumeration.
– devios1
Jul 26 '13 at 15:25
Updated answer to demo use ofObject.defineProperty
and also slimmed the function body as per @AramKocharyan.
– devios1
Jul 26 '13 at 17:54
add a comment |
There is no reason to assume that variable "undefined" is undefined. Anyone could write something like "var undefined = true;", breaking your code. And, by extending Array, you cause for..in loop to produce unexpected results. Good programmers know they have to check for..in loop for inherited values, but not everyone is a good programmer and we shall not break their code, too.
– Richard
Jul 26 '13 at 11:03
4
It would hardly break my code! Why do you think that? If someone wants to redefine undefined, then let them, though it's a pretty crazy thing to do. That's the power of JavaScript. They can also redefine Array.getLast if they like. Also, good programmers use Object.defineProperty to get around enumeration.
– devios1
Jul 26 '13 at 15:25
Updated answer to demo use ofObject.defineProperty
and also slimmed the function body as per @AramKocharyan.
– devios1
Jul 26 '13 at 17:54
There is no reason to assume that variable "undefined" is undefined. Anyone could write something like "var undefined = true;", breaking your code. And, by extending Array, you cause for..in loop to produce unexpected results. Good programmers know they have to check for..in loop for inherited values, but not everyone is a good programmer and we shall not break their code, too.
– Richard
Jul 26 '13 at 11:03
There is no reason to assume that variable "undefined" is undefined. Anyone could write something like "var undefined = true;", breaking your code. And, by extending Array, you cause for..in loop to produce unexpected results. Good programmers know they have to check for..in loop for inherited values, but not everyone is a good programmer and we shall not break their code, too.
– Richard
Jul 26 '13 at 11:03
4
4
It would hardly break my code! Why do you think that? If someone wants to redefine undefined, then let them, though it's a pretty crazy thing to do. That's the power of JavaScript. They can also redefine Array.getLast if they like. Also, good programmers use Object.defineProperty to get around enumeration.
– devios1
Jul 26 '13 at 15:25
It would hardly break my code! Why do you think that? If someone wants to redefine undefined, then let them, though it's a pretty crazy thing to do. That's the power of JavaScript. They can also redefine Array.getLast if they like. Also, good programmers use Object.defineProperty to get around enumeration.
– devios1
Jul 26 '13 at 15:25
Updated answer to demo use of
Object.defineProperty
and also slimmed the function body as per @AramKocharyan.– devios1
Jul 26 '13 at 17:54
Updated answer to demo use of
Object.defineProperty
and also slimmed the function body as per @AramKocharyan.– devios1
Jul 26 '13 at 17:54
add a comment |
I think if you only want get the element without remove, is more simple use this:
arr.slice(-1)
by the way... i didnt check performance, but i think is more simple and clean to write
add a comment |
I think if you only want get the element without remove, is more simple use this:
arr.slice(-1)
by the way... i didnt check performance, but i think is more simple and clean to write
add a comment |
I think if you only want get the element without remove, is more simple use this:
arr.slice(-1)
by the way... i didnt check performance, but i think is more simple and clean to write
I think if you only want get the element without remove, is more simple use this:
arr.slice(-1)
by the way... i didnt check performance, but i think is more simple and clean to write
edited Aug 20 '18 at 7:04
answered Aug 19 '18 at 22:05
terribleWebterribleWeb
19318
19318
add a comment |
add a comment |
I generally use underscorejs, with it you can just do
if (_.last(loc_array) === 'index.html'){
etc...
}
For me that is more semantic than loc_array.slice(-1)[0]
2
_.last
works with Lodash too.
– Rory O'Kane
Sep 6 '17 at 17:20
add a comment |
I generally use underscorejs, with it you can just do
if (_.last(loc_array) === 'index.html'){
etc...
}
For me that is more semantic than loc_array.slice(-1)[0]
2
_.last
works with Lodash too.
– Rory O'Kane
Sep 6 '17 at 17:20
add a comment |
I generally use underscorejs, with it you can just do
if (_.last(loc_array) === 'index.html'){
etc...
}
For me that is more semantic than loc_array.slice(-1)[0]
I generally use underscorejs, with it you can just do
if (_.last(loc_array) === 'index.html'){
etc...
}
For me that is more semantic than loc_array.slice(-1)[0]
answered Jan 7 '14 at 17:40
nielsniels
1,439818
1,439818
2
_.last
works with Lodash too.
– Rory O'Kane
Sep 6 '17 at 17:20
add a comment |
2
_.last
works with Lodash too.
– Rory O'Kane
Sep 6 '17 at 17:20
2
2
_.last
works with Lodash too.– Rory O'Kane
Sep 6 '17 at 17:20
_.last
works with Lodash too.– Rory O'Kane
Sep 6 '17 at 17:20
add a comment |
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop()
.
arr.pop()
is exactly as efficient as arr[arr.length-1]
, and both are the same speed as arr.push()
.
Therefore, you can get away with:
let thePop = arr.pop()
arr.push(thePop)
Which can be reduced to this (same speed):
arr.push(thePop = arr.pop())
This is twice as slow as arr[arr.length-1]
, but you don't have to stuff around with an index. That's worth gold on any day.
Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]
:
[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
arr[arr.length - 1] ------> 1 -----> 1
let myPop = arr.pop()
arr.push(myPop) ------> 2 -----> 2
arr.slice(-1).pop() ------> 36 -----> 924
arr.slice(-1)[0] ------> 36 -----> 924
[...arr].pop() ------> 120 -----> ~21,000,000 :)
The last three options, ESPECIALLY [...arr].pop()
, get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop()
probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.
Brilliant answer. Exactly what I needed when working withString.split()
– mklbtz
Oct 11 '18 at 14:46
1
If initial array can be empty, this approach will result incorrectly andwill be turned into
[undefined]
. You need to protect backward push with explicitundefined
check, something likemyPop !== undefined && arr.push(myPop)
– dhilt
Feb 6 at 8:36
add a comment |
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop()
.
arr.pop()
is exactly as efficient as arr[arr.length-1]
, and both are the same speed as arr.push()
.
Therefore, you can get away with:
let thePop = arr.pop()
arr.push(thePop)
Which can be reduced to this (same speed):
arr.push(thePop = arr.pop())
This is twice as slow as arr[arr.length-1]
, but you don't have to stuff around with an index. That's worth gold on any day.
Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]
:
[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
arr[arr.length - 1] ------> 1 -----> 1
let myPop = arr.pop()
arr.push(myPop) ------> 2 -----> 2
arr.slice(-1).pop() ------> 36 -----> 924
arr.slice(-1)[0] ------> 36 -----> 924
[...arr].pop() ------> 120 -----> ~21,000,000 :)
The last three options, ESPECIALLY [...arr].pop()
, get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop()
probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.
Brilliant answer. Exactly what I needed when working withString.split()
– mklbtz
Oct 11 '18 at 14:46
1
If initial array can be empty, this approach will result incorrectly andwill be turned into
[undefined]
. You need to protect backward push with explicitundefined
check, something likemyPop !== undefined && arr.push(myPop)
– dhilt
Feb 6 at 8:36
add a comment |
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop()
.
arr.pop()
is exactly as efficient as arr[arr.length-1]
, and both are the same speed as arr.push()
.
Therefore, you can get away with:
let thePop = arr.pop()
arr.push(thePop)
Which can be reduced to this (same speed):
arr.push(thePop = arr.pop())
This is twice as slow as arr[arr.length-1]
, but you don't have to stuff around with an index. That's worth gold on any day.
Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]
:
[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
arr[arr.length - 1] ------> 1 -----> 1
let myPop = arr.pop()
arr.push(myPop) ------> 2 -----> 2
arr.slice(-1).pop() ------> 36 -----> 924
arr.slice(-1)[0] ------> 36 -----> 924
[...arr].pop() ------> 120 -----> ~21,000,000 :)
The last three options, ESPECIALLY [...arr].pop()
, get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop()
probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop()
.
arr.pop()
is exactly as efficient as arr[arr.length-1]
, and both are the same speed as arr.push()
.
Therefore, you can get away with:
let thePop = arr.pop()
arr.push(thePop)
Which can be reduced to this (same speed):
arr.push(thePop = arr.pop())
This is twice as slow as arr[arr.length-1]
, but you don't have to stuff around with an index. That's worth gold on any day.
Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]
:
[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
arr[arr.length - 1] ------> 1 -----> 1
let myPop = arr.pop()
arr.push(myPop) ------> 2 -----> 2
arr.slice(-1).pop() ------> 36 -----> 924
arr.slice(-1)[0] ------> 36 -----> 924
[...arr].pop() ------> 120 -----> ~21,000,000 :)
The last three options, ESPECIALLY [...arr].pop()
, get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop()
probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.
answered Aug 9 '18 at 9:33
Paul ParkerPaul Parker
20018
20018
Brilliant answer. Exactly what I needed when working withString.split()
– mklbtz
Oct 11 '18 at 14:46
1
If initial array can be empty, this approach will result incorrectly andwill be turned into
[undefined]
. You need to protect backward push with explicitundefined
check, something likemyPop !== undefined && arr.push(myPop)
– dhilt
Feb 6 at 8:36
add a comment |
Brilliant answer. Exactly what I needed when working withString.split()
– mklbtz
Oct 11 '18 at 14:46
1
If initial array can be empty, this approach will result incorrectly andwill be turned into
[undefined]
. You need to protect backward push with explicitundefined
check, something likemyPop !== undefined && arr.push(myPop)
– dhilt
Feb 6 at 8:36
Brilliant answer. Exactly what I needed when working with
String.split()
– mklbtz
Oct 11 '18 at 14:46
Brilliant answer. Exactly what I needed when working with
String.split()
– mklbtz
Oct 11 '18 at 14:46
1
1
If initial array can be empty, this approach will result incorrectly and
will be turned into [undefined]
. You need to protect backward push with explicit undefined
check, something like myPop !== undefined && arr.push(myPop)
– dhilt
Feb 6 at 8:36
If initial array can be empty, this approach will result incorrectly and
will be turned into [undefined]
. You need to protect backward push with explicit undefined
check, something like myPop !== undefined && arr.push(myPop)
– dhilt
Feb 6 at 8:36
add a comment |
Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.
var array = [[1,2,3], [4,5,6], [7,8,9]]
array.slice(-1)[0]
//instead of
array[array.length-1]
//Much easier to read with nested arrays
array.slice(-1)[0].slice(-1)[0]
//instead of
array[array.length-1][array[array.length-1].length-1]
Easier is a point of view, and I wont disagree, but creating a new instance of array only to fetch some item is surely not smart.
– Guilherme Ferreira
Feb 14 '17 at 20:24
add a comment |
Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.
var array = [[1,2,3], [4,5,6], [7,8,9]]
array.slice(-1)[0]
//instead of
array[array.length-1]
//Much easier to read with nested arrays
array.slice(-1)[0].slice(-1)[0]
//instead of
array[array.length-1][array[array.length-1].length-1]
Easier is a point of view, and I wont disagree, but creating a new instance of array only to fetch some item is surely not smart.
– Guilherme Ferreira
Feb 14 '17 at 20:24
add a comment |
Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.
var array = [[1,2,3], [4,5,6], [7,8,9]]
array.slice(-1)[0]
//instead of
array[array.length-1]
//Much easier to read with nested arrays
array.slice(-1)[0].slice(-1)[0]
//instead of
array[array.length-1][array[array.length-1].length-1]
Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.
var array = [[1,2,3], [4,5,6], [7,8,9]]
array.slice(-1)[0]
//instead of
array[array.length-1]
//Much easier to read with nested arrays
array.slice(-1)[0].slice(-1)[0]
//instead of
array[array.length-1][array[array.length-1].length-1]
answered Mar 3 '16 at 12:53
Michael Falck WedelgårdMichael Falck Wedelgård
1,5711525
1,5711525
Easier is a point of view, and I wont disagree, but creating a new instance of array only to fetch some item is surely not smart.
– Guilherme Ferreira
Feb 14 '17 at 20:24
add a comment |
Easier is a point of view, and I wont disagree, but creating a new instance of array only to fetch some item is surely not smart.
– Guilherme Ferreira
Feb 14 '17 at 20:24
Easier is a point of view, and I wont disagree, but creating a new instance of array only to fetch some item is surely not smart.
– Guilherme Ferreira
Feb 14 '17 at 20:24
Easier is a point of view, and I wont disagree, but creating a new instance of array only to fetch some item is surely not smart.
– Guilherme Ferreira
Feb 14 '17 at 20:24
add a comment |
You can add a last()
function to the Array
prototype.
Array.prototype.last = function () {
return this[this.length - 1];
};
6
Remember this is a highly discouraged anti-pattern though.
– caesarsol
Mar 6 '17 at 14:43
1
@caesarsol could you please explain why or provide a link regarding this?
– eko24ive
Oct 17 '17 at 8:10
2
@eko24ive In short, you are modifying global objects which are used both in your code and in any other library present in the scripts, and that is dangerous. Moreover, you expose your code to possible breakage in case of future language additions. Some libraries in the past did it, with big regret. Have a look at this for more: stackoverflow.com/questions/14034180/…
– caesarsol
Oct 24 '17 at 8:51
See my solution later on this page. Solution is to create a wrapper function name it "w()" that returns an object which has method last() which returns the last item of the array given as argument to w(). Then the result of w() in terms of the method last() behaves like arrays would if their prototype was given this method. But it is not so you are not breaking any global functionality. Remember JavaScript is prototype-based meaning every object can have its own methods, no need to mess up the prototype if all you need is a single new method.
– Panu Logic
Jun 28 '18 at 17:56
add a comment |
You can add a last()
function to the Array
prototype.
Array.prototype.last = function () {
return this[this.length - 1];
};
6
Remember this is a highly discouraged anti-pattern though.
– caesarsol
Mar 6 '17 at 14:43
1
@caesarsol could you please explain why or provide a link regarding this?
– eko24ive
Oct 17 '17 at 8:10
2
@eko24ive In short, you are modifying global objects which are used both in your code and in any other library present in the scripts, and that is dangerous. Moreover, you expose your code to possible breakage in case of future language additions. Some libraries in the past did it, with big regret. Have a look at this for more: stackoverflow.com/questions/14034180/…
– caesarsol
Oct 24 '17 at 8:51
See my solution later on this page. Solution is to create a wrapper function name it "w()" that returns an object which has method last() which returns the last item of the array given as argument to w(). Then the result of w() in terms of the method last() behaves like arrays would if their prototype was given this method. But it is not so you are not breaking any global functionality. Remember JavaScript is prototype-based meaning every object can have its own methods, no need to mess up the prototype if all you need is a single new method.
– Panu Logic
Jun 28 '18 at 17:56
add a comment |
You can add a last()
function to the Array
prototype.
Array.prototype.last = function () {
return this[this.length - 1];
};
You can add a last()
function to the Array
prototype.
Array.prototype.last = function () {
return this[this.length - 1];
};
edited Oct 4 '17 at 7:49
alex
341k170768914
341k170768914
answered Jul 20 '15 at 8:21
trinalbadger587trinalbadger587
491518
491518
6
Remember this is a highly discouraged anti-pattern though.
– caesarsol
Mar 6 '17 at 14:43
1
@caesarsol could you please explain why or provide a link regarding this?
– eko24ive
Oct 17 '17 at 8:10
2
@eko24ive In short, you are modifying global objects which are used both in your code and in any other library present in the scripts, and that is dangerous. Moreover, you expose your code to possible breakage in case of future language additions. Some libraries in the past did it, with big regret. Have a look at this for more: stackoverflow.com/questions/14034180/…
– caesarsol
Oct 24 '17 at 8:51
See my solution later on this page. Solution is to create a wrapper function name it "w()" that returns an object which has method last() which returns the last item of the array given as argument to w(). Then the result of w() in terms of the method last() behaves like arrays would if their prototype was given this method. But it is not so you are not breaking any global functionality. Remember JavaScript is prototype-based meaning every object can have its own methods, no need to mess up the prototype if all you need is a single new method.
– Panu Logic
Jun 28 '18 at 17:56
add a comment |
6
Remember this is a highly discouraged anti-pattern though.
– caesarsol
Mar 6 '17 at 14:43
1
@caesarsol could you please explain why or provide a link regarding this?
– eko24ive
Oct 17 '17 at 8:10
2
@eko24ive In short, you are modifying global objects which are used both in your code and in any other library present in the scripts, and that is dangerous. Moreover, you expose your code to possible breakage in case of future language additions. Some libraries in the past did it, with big regret. Have a look at this for more: stackoverflow.com/questions/14034180/…
– caesarsol
Oct 24 '17 at 8:51
See my solution later on this page. Solution is to create a wrapper function name it "w()" that returns an object which has method last() which returns the last item of the array given as argument to w(). Then the result of w() in terms of the method last() behaves like arrays would if their prototype was given this method. But it is not so you are not breaking any global functionality. Remember JavaScript is prototype-based meaning every object can have its own methods, no need to mess up the prototype if all you need is a single new method.
– Panu Logic
Jun 28 '18 at 17:56
6
6
Remember this is a highly discouraged anti-pattern though.
– caesarsol
Mar 6 '17 at 14:43
Remember this is a highly discouraged anti-pattern though.
– caesarsol
Mar 6 '17 at 14:43
1
1
@caesarsol could you please explain why or provide a link regarding this?
– eko24ive
Oct 17 '17 at 8:10
@caesarsol could you please explain why or provide a link regarding this?
– eko24ive
Oct 17 '17 at 8:10
2
2
@eko24ive In short, you are modifying global objects which are used both in your code and in any other library present in the scripts, and that is dangerous. Moreover, you expose your code to possible breakage in case of future language additions. Some libraries in the past did it, with big regret. Have a look at this for more: stackoverflow.com/questions/14034180/…
– caesarsol
Oct 24 '17 at 8:51
@eko24ive In short, you are modifying global objects which are used both in your code and in any other library present in the scripts, and that is dangerous. Moreover, you expose your code to possible breakage in case of future language additions. Some libraries in the past did it, with big regret. Have a look at this for more: stackoverflow.com/questions/14034180/…
– caesarsol
Oct 24 '17 at 8:51
See my solution later on this page. Solution is to create a wrapper function name it "w()" that returns an object which has method last() which returns the last item of the array given as argument to w(). Then the result of w() in terms of the method last() behaves like arrays would if their prototype was given this method. But it is not so you are not breaking any global functionality. Remember JavaScript is prototype-based meaning every object can have its own methods, no need to mess up the prototype if all you need is a single new method.
– Panu Logic
Jun 28 '18 at 17:56
See my solution later on this page. Solution is to create a wrapper function name it "w()" that returns an object which has method last() which returns the last item of the array given as argument to w(). Then the result of w() in terms of the method last() behaves like arrays would if their prototype was given this method. But it is not so you are not breaking any global functionality. Remember JavaScript is prototype-based meaning every object can have its own methods, no need to mess up the prototype if all you need is a single new method.
– Panu Logic
Jun 28 '18 at 17:56
add a comment |
You could add a new property getter to the prototype of Array
so that it is accessible through all instances of Array
.
Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]
).
Finally you wrap it in a condition that checks whether the last
-property is still undefined
(not defined by another script that might rely on it).
if(typeof Array.prototype.last === 'undefined') {
Object.defineProperty(Array.prototype, 'last', {
get : function() {
return this[this.length - 1];
}
});
}
// Now you can access it like
[1, 2, 3].last; // => 3
// or
var test = [50, 1000];
alert(test.last); // Says '1000'
Does not work in IE ≤ 8.
Array.prototype.last
is alwaysundefined
? The if isn't working under Chrome 36
– bryc
Aug 23 '14 at 16:43
for me this is the best answer. Waaaay far the best
– Soldeplata Saketos
Jul 3 '18 at 9:19
add a comment |
You could add a new property getter to the prototype of Array
so that it is accessible through all instances of Array
.
Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]
).
Finally you wrap it in a condition that checks whether the last
-property is still undefined
(not defined by another script that might rely on it).
if(typeof Array.prototype.last === 'undefined') {
Object.defineProperty(Array.prototype, 'last', {
get : function() {
return this[this.length - 1];
}
});
}
// Now you can access it like
[1, 2, 3].last; // => 3
// or
var test = [50, 1000];
alert(test.last); // Says '1000'
Does not work in IE ≤ 8.
Array.prototype.last
is alwaysundefined
? The if isn't working under Chrome 36
– bryc
Aug 23 '14 at 16:43
for me this is the best answer. Waaaay far the best
– Soldeplata Saketos
Jul 3 '18 at 9:19
add a comment |
You could add a new property getter to the prototype of Array
so that it is accessible through all instances of Array
.
Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]
).
Finally you wrap it in a condition that checks whether the last
-property is still undefined
(not defined by another script that might rely on it).
if(typeof Array.prototype.last === 'undefined') {
Object.defineProperty(Array.prototype, 'last', {
get : function() {
return this[this.length - 1];
}
});
}
// Now you can access it like
[1, 2, 3].last; // => 3
// or
var test = [50, 1000];
alert(test.last); // Says '1000'
Does not work in IE ≤ 8.
You could add a new property getter to the prototype of Array
so that it is accessible through all instances of Array
.
Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]
).
Finally you wrap it in a condition that checks whether the last
-property is still undefined
(not defined by another script that might rely on it).
if(typeof Array.prototype.last === 'undefined') {
Object.defineProperty(Array.prototype, 'last', {
get : function() {
return this[this.length - 1];
}
});
}
// Now you can access it like
[1, 2, 3].last; // => 3
// or
var test = [50, 1000];
alert(test.last); // Says '1000'
Does not work in IE ≤ 8.
edited Jul 6 '14 at 22:26
answered Jul 6 '14 at 19:27
MatmarbonMatmarbon
2,81511937
2,81511937
Array.prototype.last
is alwaysundefined
? The if isn't working under Chrome 36
– bryc
Aug 23 '14 at 16:43
for me this is the best answer. Waaaay far the best
– Soldeplata Saketos
Jul 3 '18 at 9:19
add a comment |
Array.prototype.last
is alwaysundefined
? The if isn't working under Chrome 36
– bryc
Aug 23 '14 at 16:43
for me this is the best answer. Waaaay far the best
– Soldeplata Saketos
Jul 3 '18 at 9:19
Array.prototype.last
is always undefined
? The if isn't working under Chrome 36– bryc
Aug 23 '14 at 16:43
Array.prototype.last
is always undefined
? The if isn't working under Chrome 36– bryc
Aug 23 '14 at 16:43
for me this is the best answer. Waaaay far the best
– Soldeplata Saketos
Jul 3 '18 at 9:19
for me this is the best answer. Waaaay far the best
– Soldeplata Saketos
Jul 3 '18 at 9:19
add a comment |
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).
It is the best solution in terms of performance. But it is not the best in terms of code-quality. It is way too easy to type: var lastElement = arr[arr.lenght - 1];
– Panu Logic
Jun 28 '18 at 17:59
add a comment |
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).
It is the best solution in terms of performance. But it is not the best in terms of code-quality. It is way too easy to type: var lastElement = arr[arr.lenght - 1];
– Panu Logic
Jun 28 '18 at 17:59
add a comment |
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).
edited Aug 2 '18 at 22:50
answered Jun 18 '14 at 12:33
Alexander BurakevychAlexander Burakevych
1,64811421
1,64811421
It is the best solution in terms of performance. But it is not the best in terms of code-quality. It is way too easy to type: var lastElement = arr[arr.lenght - 1];
– Panu Logic
Jun 28 '18 at 17:59
add a comment |
It is the best solution in terms of performance. But it is not the best in terms of code-quality. It is way too easy to type: var lastElement = arr[arr.lenght - 1];
– Panu Logic
Jun 28 '18 at 17:59
It is the best solution in terms of performance. But it is not the best in terms of code-quality. It is way too easy to type: var lastElement = arr[arr.lenght - 1];
– Panu Logic
Jun 28 '18 at 17:59
It is the best solution in terms of performance. But it is not the best in terms of code-quality. It is way too easy to type: var lastElement = arr[arr.lenght - 1];
– Panu Logic
Jun 28 '18 at 17:59
add a comment |
EDITED:
Recently I came up with one more solution which I now think is the best for my needs:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
With the above definition in effect I can now say:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
The name "w" stands for "wrapper".
You can see how you could easily add more
methods besides 'last()' to this wrapper.
I say "best for my needs", because this allows
me to easily add other such "helper methods"
to any JavaScript built-in type. What comes
to mind are the car() and cdr() of Lisp for
instance.
and a 4th one for fun and very readable :myArray.reverse()[0]
– mickro
Jun 27 '18 at 14:48
Why use a wrapper? If you have to call aw
function just make the function return the last item.
– bfred.it
Sep 19 '18 at 4:32
add a comment |
EDITED:
Recently I came up with one more solution which I now think is the best for my needs:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
With the above definition in effect I can now say:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
The name "w" stands for "wrapper".
You can see how you could easily add more
methods besides 'last()' to this wrapper.
I say "best for my needs", because this allows
me to easily add other such "helper methods"
to any JavaScript built-in type. What comes
to mind are the car() and cdr() of Lisp for
instance.
and a 4th one for fun and very readable :myArray.reverse()[0]
– mickro
Jun 27 '18 at 14:48
Why use a wrapper? If you have to call aw
function just make the function return the last item.
– bfred.it
Sep 19 '18 at 4:32
add a comment |
EDITED:
Recently I came up with one more solution which I now think is the best for my needs:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
With the above definition in effect I can now say:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
The name "w" stands for "wrapper".
You can see how you could easily add more
methods besides 'last()' to this wrapper.
I say "best for my needs", because this allows
me to easily add other such "helper methods"
to any JavaScript built-in type. What comes
to mind are the car() and cdr() of Lisp for
instance.
EDITED:
Recently I came up with one more solution which I now think is the best for my needs:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
With the above definition in effect I can now say:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
The name "w" stands for "wrapper".
You can see how you could easily add more
methods besides 'last()' to this wrapper.
I say "best for my needs", because this allows
me to easily add other such "helper methods"
to any JavaScript built-in type. What comes
to mind are the car() and cdr() of Lisp for
instance.
edited Feb 6 at 8:45
dhilt
7,88742141
7,88742141
answered Mar 18 '18 at 18:50
Panu LogicPanu Logic
631513
631513
and a 4th one for fun and very readable :myArray.reverse()[0]
– mickro
Jun 27 '18 at 14:48
Why use a wrapper? If you have to call aw
function just make the function return the last item.
– bfred.it
Sep 19 '18 at 4:32
add a comment |
and a 4th one for fun and very readable :myArray.reverse()[0]
– mickro
Jun 27 '18 at 14:48
Why use a wrapper? If you have to call aw
function just make the function return the last item.
– bfred.it
Sep 19 '18 at 4:32
and a 4th one for fun and very readable :
myArray.reverse()[0]
– mickro
Jun 27 '18 at 14:48
and a 4th one for fun and very readable :
myArray.reverse()[0]
– mickro
Jun 27 '18 at 14:48
Why use a wrapper? If you have to call a
w
function just make the function return the last item.– bfred.it
Sep 19 '18 at 4:32
Why use a wrapper? If you have to call a
w
function just make the function return the last item.– bfred.it
Sep 19 '18 at 4:32
add a comment |
I think the easiest and super inefficient way is:
var array = ['fenerbahce','arsenal','milan'];
var reversed_array = array.reverse(); //inverts array [milan,arsenal,fenerbahce]
console.log(reversed_array[0]) // result is "milan".
39
This solution takes O(n) more memory and takes O(n) time. It's really not the ideal solution.
– hlin117
Jul 6 '15 at 18:09
10
This is highly inefficient. Don't do this.
– marton78
Jul 22 '15 at 12:17
2
Do not do this , it is just knowledge :)
– Osman Erdi
Mar 29 '16 at 23:56
2
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:27
But it sure is easy.
– Andy
May 4 '18 at 5:49
add a comment |
I think the easiest and super inefficient way is:
var array = ['fenerbahce','arsenal','milan'];
var reversed_array = array.reverse(); //inverts array [milan,arsenal,fenerbahce]
console.log(reversed_array[0]) // result is "milan".
39
This solution takes O(n) more memory and takes O(n) time. It's really not the ideal solution.
– hlin117
Jul 6 '15 at 18:09
10
This is highly inefficient. Don't do this.
– marton78
Jul 22 '15 at 12:17
2
Do not do this , it is just knowledge :)
– Osman Erdi
Mar 29 '16 at 23:56
2
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:27
But it sure is easy.
– Andy
May 4 '18 at 5:49
add a comment |
I think the easiest and super inefficient way is:
var array = ['fenerbahce','arsenal','milan'];
var reversed_array = array.reverse(); //inverts array [milan,arsenal,fenerbahce]
console.log(reversed_array[0]) // result is "milan".
I think the easiest and super inefficient way is:
var array = ['fenerbahce','arsenal','milan'];
var reversed_array = array.reverse(); //inverts array [milan,arsenal,fenerbahce]
console.log(reversed_array[0]) // result is "milan".
edited Apr 23 '17 at 23:57
answered Oct 27 '14 at 3:32
Osman ErdiOsman Erdi
1,01511122
1,01511122
39
This solution takes O(n) more memory and takes O(n) time. It's really not the ideal solution.
– hlin117
Jul 6 '15 at 18:09
10
This is highly inefficient. Don't do this.
– marton78
Jul 22 '15 at 12:17
2
Do not do this , it is just knowledge :)
– Osman Erdi
Mar 29 '16 at 23:56
2
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:27
But it sure is easy.
– Andy
May 4 '18 at 5:49
add a comment |
39
This solution takes O(n) more memory and takes O(n) time. It's really not the ideal solution.
– hlin117
Jul 6 '15 at 18:09
10
This is highly inefficient. Don't do this.
– marton78
Jul 22 '15 at 12:17
2
Do not do this , it is just knowledge :)
– Osman Erdi
Mar 29 '16 at 23:56
2
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:27
But it sure is easy.
– Andy
May 4 '18 at 5:49
39
39
This solution takes O(n) more memory and takes O(n) time. It's really not the ideal solution.
– hlin117
Jul 6 '15 at 18:09
This solution takes O(n) more memory and takes O(n) time. It's really not the ideal solution.
– hlin117
Jul 6 '15 at 18:09
10
10
This is highly inefficient. Don't do this.
– marton78
Jul 22 '15 at 12:17
This is highly inefficient. Don't do this.
– marton78
Jul 22 '15 at 12:17
2
2
Do not do this , it is just knowledge :)
– Osman Erdi
Mar 29 '16 at 23:56
Do not do this , it is just knowledge :)
– Osman Erdi
Mar 29 '16 at 23:56
2
2
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:27
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:27
But it sure is easy.
– Andy
May 4 '18 at 5:49
But it sure is easy.
– Andy
May 4 '18 at 5:49
add a comment |
I'll suggest to create helper function and reuse it every time, you'll need it. Lets make function more general to be able to get not only last item, but also second from the last and so on.
function last(arr, i) {
var i = i || 0;
return arr[arr.length - (1 + i)];
}
Usage is simple
var arr = [1,2,3,4,5];
last(arr); //5
last(arr, 1); //4
last(arr, 9); //undefined
Now, lets solve the original issue
Grab second to last item form array. If the last item in the loc_array is "index.html" grab the third to last item instead.
Next line does the job
last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
So, you'll need to rewrite
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
in this way
var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === 'index.html' ? 2 : 1))));
or use additional variable to increase readability
var nodeName = last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));
See my answer which is very similar. Instead of creating a function "last()" I create function "w(theArray)" which returns an object which has the METHOD "last()" .
– Panu Logic
Jun 28 '18 at 17:49
add a comment |
I'll suggest to create helper function and reuse it every time, you'll need it. Lets make function more general to be able to get not only last item, but also second from the last and so on.
function last(arr, i) {
var i = i || 0;
return arr[arr.length - (1 + i)];
}
Usage is simple
var arr = [1,2,3,4,5];
last(arr); //5
last(arr, 1); //4
last(arr, 9); //undefined
Now, lets solve the original issue
Grab second to last item form array. If the last item in the loc_array is "index.html" grab the third to last item instead.
Next line does the job
last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
So, you'll need to rewrite
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
in this way
var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === 'index.html' ? 2 : 1))));
or use additional variable to increase readability
var nodeName = last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));
See my answer which is very similar. Instead of creating a function "last()" I create function "w(theArray)" which returns an object which has the METHOD "last()" .
– Panu Logic
Jun 28 '18 at 17:49
add a comment |
I'll suggest to create helper function and reuse it every time, you'll need it. Lets make function more general to be able to get not only last item, but also second from the last and so on.
function last(arr, i) {
var i = i || 0;
return arr[arr.length - (1 + i)];
}
Usage is simple
var arr = [1,2,3,4,5];
last(arr); //5
last(arr, 1); //4
last(arr, 9); //undefined
Now, lets solve the original issue
Grab second to last item form array. If the last item in the loc_array is "index.html" grab the third to last item instead.
Next line does the job
last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
So, you'll need to rewrite
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
in this way
var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === 'index.html' ? 2 : 1))));
or use additional variable to increase readability
var nodeName = last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));
I'll suggest to create helper function and reuse it every time, you'll need it. Lets make function more general to be able to get not only last item, but also second from the last and so on.
function last(arr, i) {
var i = i || 0;
return arr[arr.length - (1 + i)];
}
Usage is simple
var arr = [1,2,3,4,5];
last(arr); //5
last(arr, 1); //4
last(arr, 9); //undefined
Now, lets solve the original issue
Grab second to last item form array. If the last item in the loc_array is "index.html" grab the third to last item instead.
Next line does the job
last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
So, you'll need to rewrite
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
in this way
var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === 'index.html' ? 2 : 1))));
or use additional variable to increase readability
var nodeName = last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));
answered Apr 20 '17 at 10:59
Michael KapusteyMichael Kapustey
10616
10616
See my answer which is very similar. Instead of creating a function "last()" I create function "w(theArray)" which returns an object which has the METHOD "last()" .
– Panu Logic
Jun 28 '18 at 17:49
add a comment |
See my answer which is very similar. Instead of creating a function "last()" I create function "w(theArray)" which returns an object which has the METHOD "last()" .
– Panu Logic
Jun 28 '18 at 17:49
See my answer which is very similar. Instead of creating a function "last()" I create function "w(theArray)" which returns an object which has the METHOD "last()" .
– Panu Logic
Jun 28 '18 at 17:49
See my answer which is very similar. Instead of creating a function "last()" I create function "w(theArray)" which returns an object which has the METHOD "last()" .
– Panu Logic
Jun 28 '18 at 17:49
add a comment |
In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.
Syntax:
arr.lastItem // get last item
arr.lastItem = 'value' // set last item
arr.lastIndex // get last index
You can use polyfill.
Proposal author: Keith Cirkel(chai autor)
add a comment |
In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.
Syntax:
arr.lastItem // get last item
arr.lastItem = 'value' // set last item
arr.lastIndex // get last index
You can use polyfill.
Proposal author: Keith Cirkel(chai autor)
add a comment |
In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.
Syntax:
arr.lastItem // get last item
arr.lastItem = 'value' // set last item
arr.lastIndex // get last index
You can use polyfill.
Proposal author: Keith Cirkel(chai autor)
In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.
Syntax:
arr.lastItem // get last item
arr.lastItem = 'value' // set last item
arr.lastIndex // get last index
You can use polyfill.
Proposal author: Keith Cirkel(chai autor)
answered Aug 30 '18 at 19:31
Илья ЗеленькоИлья Зеленько
1,3231718
1,3231718
add a comment |
add a comment |
The simple way to get last item of array:
var last_item = loc_array.reverse()[0];
Of course, we need to check to make sure array has at least one item first.
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– Vizllx
Nov 22 '18 at 3:30
The question is "How to get last item in an array", and my solution should works. :)
– Cong Nguyen
Nov 22 '18 at 3:56
1
this is the slowest way to get the last element... what if the array has a million elements?
– Deian
Dec 14 '18 at 19:07
add a comment |
The simple way to get last item of array:
var last_item = loc_array.reverse()[0];
Of course, we need to check to make sure array has at least one item first.
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– Vizllx
Nov 22 '18 at 3:30
The question is "How to get last item in an array", and my solution should works. :)
– Cong Nguyen
Nov 22 '18 at 3:56
1
this is the slowest way to get the last element... what if the array has a million elements?
– Deian
Dec 14 '18 at 19:07
add a comment |
The simple way to get last item of array:
var last_item = loc_array.reverse()[0];
Of course, we need to check to make sure array has at least one item first.
The simple way to get last item of array:
var last_item = loc_array.reverse()[0];
Of course, we need to check to make sure array has at least one item first.
edited Nov 22 '18 at 3:58
answered Nov 22 '18 at 2:28
Cong NguyenCong Nguyen
52048
52048
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– Vizllx
Nov 22 '18 at 3:30
The question is "How to get last item in an array", and my solution should works. :)
– Cong Nguyen
Nov 22 '18 at 3:56
1
this is the slowest way to get the last element... what if the array has a million elements?
– Deian
Dec 14 '18 at 19:07
add a comment |
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– Vizllx
Nov 22 '18 at 3:30
The question is "How to get last item in an array", and my solution should works. :)
– Cong Nguyen
Nov 22 '18 at 3:56
1
this is the slowest way to get the last element... what if the array has a million elements?
– Deian
Dec 14 '18 at 19:07
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– Vizllx
Nov 22 '18 at 3:30
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– Vizllx
Nov 22 '18 at 3:30
The question is "How to get last item in an array", and my solution should works. :)
– Cong Nguyen
Nov 22 '18 at 3:56
The question is "How to get last item in an array", and my solution should works. :)
– Cong Nguyen
Nov 22 '18 at 3:56
1
1
this is the slowest way to get the last element... what if the array has a million elements?
– Deian
Dec 14 '18 at 19:07
this is the slowest way to get the last element... what if the array has a million elements?
– Deian
Dec 14 '18 at 19:07
add a comment |
Using lodash _.last(array) Gets the last element of array.
data = [1,2,3]
last = _.last(data)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
add a comment |
Using lodash _.last(array) Gets the last element of array.
data = [1,2,3]
last = _.last(data)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
add a comment |
Using lodash _.last(array) Gets the last element of array.
data = [1,2,3]
last = _.last(data)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Using lodash _.last(array) Gets the last element of array.
data = [1,2,3]
last = _.last(data)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
data = [1,2,3]
last = _.last(data)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
data = [1,2,3]
last = _.last(data)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
answered Sep 20 '17 at 20:31
DeanoDeano
4,565103872
4,565103872
add a comment |
add a comment |
You can achieve this issue also without extracting an array from the url
This is my alternative
var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();
!Greetings¡
add a comment |
You can achieve this issue also without extracting an array from the url
This is my alternative
var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();
!Greetings¡
add a comment |
You can achieve this issue also without extracting an array from the url
This is my alternative
var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();
!Greetings¡
You can achieve this issue also without extracting an array from the url
This is my alternative
var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();
!Greetings¡
answered Sep 15 '14 at 2:55
snaphumansnaphuman
1114
1114
add a comment |
add a comment |
This can be done with lodash _.last
or _.nth
:
var data = [1, 2, 3, 4]
var last = _.nth(data, -1)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
add a comment |
This can be done with lodash _.last
or _.nth
:
var data = [1, 2, 3, 4]
var last = _.nth(data, -1)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
add a comment |
This can be done with lodash _.last
or _.nth
:
var data = [1, 2, 3, 4]
var last = _.nth(data, -1)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
This can be done with lodash _.last
or _.nth
:
var data = [1, 2, 3, 4]
var last = _.nth(data, -1)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
var data = [1, 2, 3, 4]
var last = _.nth(data, -1)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
var data = [1, 2, 3, 4]
var last = _.nth(data, -1)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
answered Nov 22 '18 at 6:26
Yi-Ting LiuYi-Ting Liu
1,0462623
1,0462623
add a comment |
add a comment |
Using ES6/ES2015 spread operator (...) you can do the following way.
const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)
Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.
9
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:26
@slang, agree. If you are doing hundreds to millions operations then you have to consider not to do it this way, but if you have to do it only several time than nobody will notice that. This example provides 'pure' call without changing actual data array.
– Vlad Bezden
Apr 16 '17 at 20:21
add a comment |
Using ES6/ES2015 spread operator (...) you can do the following way.
const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)
Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.
9
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:26
@slang, agree. If you are doing hundreds to millions operations then you have to consider not to do it this way, but if you have to do it only several time than nobody will notice that. This example provides 'pure' call without changing actual data array.
– Vlad Bezden
Apr 16 '17 at 20:21
add a comment |
Using ES6/ES2015 spread operator (...) you can do the following way.
const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)
Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.
Using ES6/ES2015 spread operator (...) you can do the following way.
const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)
Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.
const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)
const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)
answered Mar 17 '17 at 19:14
Vlad BezdenVlad Bezden
29.4k10128114
29.4k10128114
9
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:26
@slang, agree. If you are doing hundreds to millions operations then you have to consider not to do it this way, but if you have to do it only several time than nobody will notice that. This example provides 'pure' call without changing actual data array.
– Vlad Bezden
Apr 16 '17 at 20:21
add a comment |
9
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:26
@slang, agree. If you are doing hundreds to millions operations then you have to consider not to do it this way, but if you have to do it only several time than nobody will notice that. This example provides 'pure' call without changing actual data array.
– Vlad Bezden
Apr 16 '17 at 20:21
9
9
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:26
Reversing an entire array just to get the last element is super inefficient.
– slang
Apr 16 '17 at 19:26
@slang, agree. If you are doing hundreds to millions operations then you have to consider not to do it this way, but if you have to do it only several time than nobody will notice that. This example provides 'pure' call without changing actual data array.
– Vlad Bezden
Apr 16 '17 at 20:21
@slang, agree. If you are doing hundreds to millions operations then you have to consider not to do it this way, but if you have to do it only several time than nobody will notice that. This example provides 'pure' call without changing actual data array.
– Vlad Bezden
Apr 16 '17 at 20:21
add a comment |
There is also a npm module, that add last
to Array.prototype
npm install array-prototype-last --save
usage
require('array-prototype-last');
[1, 2, 3].last; //=> 3
.last; //=> undefined
source of function?
– Matrix
Aug 1 '17 at 11:12
1
github.com/qialex/array-prototype-last/blob/master/index.js - it is here
– qiAlex
Aug 1 '17 at 13:34
it's simalar to this?Array.prototype.last = function(){ return this[this.length - 1]; }
+Object.defineProperty(Array.prototype, 'last', {enumerable: false});
– Matrix
Aug 1 '17 at 14:17
1
in your example last is function you should call it like ['a', 'b'].last() // 'b', while in module last is property and you can call it like ['a', 'b'].last // 'b'
– qiAlex
Aug 1 '17 at 15:11
1
yes, it is a function called each time
– qiAlex
Aug 1 '17 at 17:06
|
show 1 more comment
There is also a npm module, that add last
to Array.prototype
npm install array-prototype-last --save
usage
require('array-prototype-last');
[1, 2, 3].last; //=> 3
.last; //=> undefined
source of function?
– Matrix
Aug 1 '17 at 11:12
1
github.com/qialex/array-prototype-last/blob/master/index.js - it is here
– qiAlex
Aug 1 '17 at 13:34
it's simalar to this?Array.prototype.last = function(){ return this[this.length - 1]; }
+Object.defineProperty(Array.prototype, 'last', {enumerable: false});
– Matrix
Aug 1 '17 at 14:17
1
in your example last is function you should call it like ['a', 'b'].last() // 'b', while in module last is property and you can call it like ['a', 'b'].last // 'b'
– qiAlex
Aug 1 '17 at 15:11
1
yes, it is a function called each time
– qiAlex
Aug 1 '17 at 17:06
|
show 1 more comment
There is also a npm module, that add last
to Array.prototype
npm install array-prototype-last --save
usage
require('array-prototype-last');
[1, 2, 3].last; //=> 3
.last; //=> undefined
There is also a npm module, that add last
to Array.prototype
npm install array-prototype-last --save
usage
require('array-prototype-last');
[1, 2, 3].last; //=> 3
.last; //=> undefined
answered Jul 28 '17 at 6:05
qiAlexqiAlex
2,0261724
2,0261724
source of function?
– Matrix
Aug 1 '17 at 11:12
1
github.com/qialex/array-prototype-last/blob/master/index.js - it is here
– qiAlex
Aug 1 '17 at 13:34
it's simalar to this?Array.prototype.last = function(){ return this[this.length - 1]; }
+Object.defineProperty(Array.prototype, 'last', {enumerable: false});
– Matrix
Aug 1 '17 at 14:17
1
in your example last is function you should call it like ['a', 'b'].last() // 'b', while in module last is property and you can call it like ['a', 'b'].last // 'b'
– qiAlex
Aug 1 '17 at 15:11
1
yes, it is a function called each time
– qiAlex
Aug 1 '17 at 17:06
|
show 1 more comment
source of function?
– Matrix
Aug 1 '17 at 11:12
1
github.com/qialex/array-prototype-last/blob/master/index.js - it is here
– qiAlex
Aug 1 '17 at 13:34
it's simalar to this?Array.prototype.last = function(){ return this[this.length - 1]; }
+Object.defineProperty(Array.prototype, 'last', {enumerable: false});
– Matrix
Aug 1 '17 at 14:17
1
in your example last is function you should call it like ['a', 'b'].last() // 'b', while in module last is property and you can call it like ['a', 'b'].last // 'b'
– qiAlex
Aug 1 '17 at 15:11
1
yes, it is a function called each time
– qiAlex
Aug 1 '17 at 17:06
source of function?
– Matrix
Aug 1 '17 at 11:12
source of function?
– Matrix
Aug 1 '17 at 11:12
1
1
github.com/qialex/array-prototype-last/blob/master/index.js - it is here
– qiAlex
Aug 1 '17 at 13:34
github.com/qialex/array-prototype-last/blob/master/index.js - it is here
– qiAlex
Aug 1 '17 at 13:34
it's simalar to this?
Array.prototype.last = function(){ return this[this.length - 1]; }
+ Object.defineProperty(Array.prototype, 'last', {enumerable: false});
– Matrix
Aug 1 '17 at 14:17
it's simalar to this?
Array.prototype.last = function(){ return this[this.length - 1]; }
+ Object.defineProperty(Array.prototype, 'last', {enumerable: false});
– Matrix
Aug 1 '17 at 14:17
1
1
in your example last is function you should call it like ['a', 'b'].last() // 'b', while in module last is property and you can call it like ['a', 'b'].last // 'b'
– qiAlex
Aug 1 '17 at 15:11
in your example last is function you should call it like ['a', 'b'].last() // 'b', while in module last is property and you can call it like ['a', 'b'].last // 'b'
– qiAlex
Aug 1 '17 at 15:11
1
1
yes, it is a function called each time
– qiAlex
Aug 1 '17 at 17:06
yes, it is a function called each time
– qiAlex
Aug 1 '17 at 17:06
|
show 1 more comment
1 2
next
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3216013%2fget-the-last-item-in-an-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown