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 trialAnthony Box
7,435 PointsUsing 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
Anthony Box
7,435 Pointshttps://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
19,699 PointsThe 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
7,435 PointsMy mistake, I was asking why you would use one over another in the problem above ^^
Steven Parker
229,732 PointsI 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.
Steven Parker
229,732 PointsSteven Parker
229,732 PointsCould 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.