Someone asked a question today about figuring out to select certain elements within an array from I to the end of the array and it made me wonder how to do that with the filter
method.
One of the solutions that someone gave was to use slice
and I understand that you're able to select from index to index, but how would you implement the filter
method to do the same thing?
Example
let arr = ['bug', 'cat', 'dog', 'flea', 'bat', 'hat', 'rat'];
let newArr = arr.filter(element => element >= element.indexOf(3));
console.log(newArr);
This is what I came up with, it doesn't work, but the idea is to select all strings that have an index of 3 or greater and return them into another array.
The runtime passes the index to the filter callback:
let newArr = arr.filter((element, index) => index >= 3);
Performance-wise you're still making a new array and copying values, so it's about the same as .slice()
.