I definitely recommend regularly refreshing yourself on definitions of common methods used in Javascript, for example Array.prototype.filter()
Consider this code:
|
1 2 3 4 5 6 7 8 |
const checkNames = (names: string[]) => { const checkedNames = [...names] // remove Darryl because he is a loser checkedNames.filter((name) => name.toLowerCase() !== 'darryl') return checkedNames } |
If I saw this code I would think that the author is probably mistaken about how filter works. In some cases array methods will mutate the original array, for example Array.prototype.sort(), but filter does not operate in this way, filter will return a new array in memory, so in this example the checking logic does not change the end result.
What we need to do is:
|
1 2 3 4 5 6 7 8 |
const checkNames = (names: string[]) => { let checkedNames = [...names] // remove Darryl because he is a loser checkedNames = checkedNames.filter((name) => name.toLowerCase() !== 'darryl') return checkedNames } |
or…
|
1 2 |
const checkNames = (names: string[]) => names.filter((name) => name.toLowerCase() !== 'darryl') |
Because we now assign/ return the array returned by filter, we will actually change the end result in this case.