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

Daiane Silva
Daiane Silva
5,668 Points

Well, I can remove items from the beginning and the end of my array, but If I want to remove the item in the middle?

var number = [1, 2, 3, 4] I want to remove number[2] but keep the rest, what should I do?

1 Answer

var indexToRemove= array.indexOf(2); -> this returns the index of number 2 Then remove it with splice: if (indexToRemove > -1) { array.splice(indexToRemove, 1); }

second param refers to the amount of elements you want to remove.