How can I get the first element from my stack here is my code

var stack = []; stack.push(id1); stack.push(id2); 

I know there is something like peek in java. Is there any similar method in JS using which i can get the topmost element?

12

6 Answers

To check the topmost element unfortunately you must explicitly index it

var top = stack[stack.length-1]; 

the syntax stack[-1] (that would work in Python) doesn't work: negative indexes are valid only as parameters to slice call.

// The same as stack[stack.length-1], just slower and NOT idiomatic var top = stack.slice(-1)[0]; 

To extract an element there is however pop:

// Add two top-most elements of the stack var a = stack.pop(); var b = stack.pop(); stack.push(a + b); 
9
var stack = []; stack.push("id1"); stack.push("id2"); console.log(stack[stack.length-1]); // the top element console.log(stack.length); //size
0

Edited 2022:

Now you can just use stack.at(-1)


If you just need one edge of your stack (head or tail is not matter) use it reversed:

I mean :

peek() become array[0],
unshift(v) become push()
shift() become pop()

some code:

class Stack{ constructor(... args ){ this.store = [... args.reverse()]; } peek(){ return this.store[0]; } push(value){ return this.store.unshift(value); } pop(){ return this.store.shift(); } } const stack = new Stack(1,2,3); stack.push(4); console.log(stack.peek()); stack.pop(); console.log(stack.peek())

or shorter

function Stack(...rest){ var store = [... rest.reverse() ]; return { push:(v)=> store.unshift(v) , pop : _ => store.shift(), peek: _ => store[0] } } var stack = Stack(1,2,3); console.log(stack.peek()); stack.push(4); console.log(stack.peek()); stack.pop(), stack.pop(); console.log(stack.peek());
5

I just want to add here the .at prototype function. Documentation is found here:

So, to get the peek is as simple as:

[array].at(-1); 

Example:

const stack = []; stack.push("sample1"); stack.push("sample2"); console.log(stack.at(-1)) // sample2 
var stackArr = [1,2,3,4]; console.log(stackArr[stackArr.length-1]); //expected output is 4;
 var stack = []; stack.push("id1"); stack.push("id2"); var topObj = stack[0] console.log(topObj) 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy