Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAbe Layee
8,378 PointsIs it possible to specify which item to remove from an array using the pop() or shift() method.
I want to know if I can remove a special element within an array using the pop() and method(). For example, let say if I want to remove shoes using the pop() method. How can I do this? I know JavaScript has remove() method which removes element from the dom.
var items = ['Hat', 'Ball', 'Shoes'];
var lastItem = items.pop();
// lastItem now holds 'Shoes'
// and items is now ['Hat', 'Ball']
2 Answers
Jacob Mishkin
23,118 PointsIt can be done. take a look at the code below:
var items = ['Hat', 'Ball', 'Shoes']; // your array
var index = items.indexOf('Ball'); //create a new var and use the indexOf() method and choose what you want removed
if ( index > -1 ){ // you need a conditional statement to use the splice method
items.splice(index, 1);
}
and there you go. If you have any other questions please ask. that's what we are here for.
Abe Layee
8,378 PointsThank you for your quick reply. I am little confused about the splice part ,but I'll look it up on Google.
Jacob Mishkin
23,118 PointsNo worries man. here are a couple of good reads:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
http://stackoverflow.com/questions/5767325/remove-specific-element-from-an-array
Happy Coding.