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 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 => 
  this.setState({
    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.

https://medium.com/@justintulk/javascript-performance-array-slice-vs-array-filter-4573d726aacb

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.