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 React by Example Building the Application Removing Names From the List

Wen Jie Lim
Wen Jie Lim
1,264 Points

Why use .slice instead of .filter?

To me, using Array.slice() in this case is a little gimmicky because you have to call it twice, plus have to think the logic through.

We could just use Array.filter() and do like:

removeGuestAt = indexToChange => 
    guests: this.state.guests.filter((guest, index) => index!== indexToRemove)

Just out of curiosity, does Array.slice() have any advantage over Array.filter(), say, performance?

1 Answer

I think the one performance disadvantage of using filter over slice is that the former has to loop through each item in the array before it finishes. Slicing on large heavy arrays would probably serve as preference here, however with smaller amounts, the performance would probably be minor if noticeable at all. Quick read a user did testing the two in the link below.


As highlighted at the end of the article, I think what's critical regarding any final code decision is both readability and the ability to scale. I actually wrote my solution using splice in which I utilized the 'prevState' callback to manipulate the array and then return it again.