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 trial

JavaScript

Anthony Box
Anthony Box
7,435 Points

Using slice over filter

When removing by index from the state, why would we use splicing over filtering by index? Is it convention or efficiency? ex. filter((guest, i) => return index == index

Steven Parker
Steven Parker
229,732 Points

Could you give a bit more code for context, and also show the alternative you are comparing it with?

If this relates to a course, a link to the course page would also be helpful.

Anthony Box
Anthony Box
7,435 Points

https://teamtreehouse.com/library/removing-names-from-the-list. Specifically, I was attempting to compare the efficacy of filter vs splice when removing elements from the state of the array. guests: [ ...this.state.guests.slice(0,index), ...this.state.guests.slice(index+1) ] vs. filter((guests, i) => return index (!)= index..

2 Answers

The biggest difference is that the filter method creates a new array containing the filtered values, whereas the splice method will edit the existing array directly. These two methods are not interchangeable even though they have similarities. You can write code to change the initial array variable to the new filtered array, which is fine; it's just more verbose than using the splice method.

Anthony Box
Anthony Box
7,435 Points

My mistake, I was asking why you would use one over another in the problem above ^^

Steven Parker
Steven Parker
229,732 Points

I think "slice" and "filter" could be used interchangeably here in modern browsers. The only advantages I can think of to "slice" is that the pattern of "before/after" for removing item(s) is one that would be readily recognized by experienced readers, and support for "slice" has been around since JS1.2, where "filter" was introduced in JS1.6.

Amber's comments relate to "splice" instead of "slice", but they remind me that "splice" might also be a good (and potentially superior) choice here, since the objective is to modify the array anyway.

One thing to keep in mind about the methods shown in course lectures is that they are chosen for clarity and not optimal performance, particularly when an optimal solution might employ a method that has not been introduced in the current course or its prerequisites.