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

Howie Yeo
PLUS
Howie Yeo
Courses Plus Student 3,639 Points

Removing more than 1 element using pop and shift method?

Hi, I am wondering if there is a way to remove more than 1 element from the array using pop and shift method?

3 Answers

You could mimic the behavior of .pop() or .shift() for multiple elements using .splice() (not to be confused with .slice()):

arrayName.splice(startIndex, deleteHowMany)

To return elements deleted from the beginning, use a start index of 0:

var arr = ['a', 'b', 'c', 'd'];
var first2 = arr.splice(0, 2); // first2 is [ "a", "b" ] 
// arr is now [ "c", "d" ]

To return elements deleted from the end, use a negative index (-1 for last, -2 for next-to-last, etc):

Array [ "a", "b", "c", "d" ]
var last2 = arr.splice(-2, 2); // last2 is [ "c", "d" ] 
// arr is now [ "a", "b" ]

here is a link to the MDN doc page for splice.

rydavim
rydavim
18,766 Points

You could use a loop to remove multiple items from an array using pop and shift, but each call may only remove a single element.

If you'd like to remove multiple elements perhaps splice might work better for you?

You can create a function for this purpose. Like I did here :

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function removeItems(arr, item) {
    for ( var i = 0; i < item; i++ ) {
        arr.pop();
    }
}

removeItems(numbers, 2);