Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Removing Items From Arrays

Abe Layee
Abe Layee
8,378 Points

Is 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

It 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
Abe Layee
8,378 Points

Thank you for your quick reply. I am little confused about the splice part ,but I'll look it up on Google.