JavaScript

Anthony Box
Anthony Box
5,578 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
97,859 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
5,578 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

Amber Cyr
Amber Cyr
16,083 Points

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
5,578 Points

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

Steven Parker
Steven Parker
97,859 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.