0

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.

1
  • appreciate that Commented Apr 25, 2019 at 19:47

4 Answers 4

5

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().

Sign up to request clarification or add additional context in comments.

2 Comments

or index > 2.
ahh gotcha, that was pretty simple, i appreciate that
1

You should create a function with the filter criteria:

let arr = ['bug', 'cat', 'dog', 'flea', 'bat', 'hat', 'rat'];

function filterCriteria(item) {
  return item >= someValue;
}

function someFunction() {
  return arr.filter(filterCriteria);
}

"someFunction" will return the array filtered

Comments

1

While you are visiting every item, you could use a counter and decrement it until the counter reaches zero. Then take this values.

const
    fromIndex = i => _ => !i || !i--,
    array = ['bug', 'cat', 'dog', 'flea', 'bat', 'hat', 'rat'],
    result = array.filter(fromIndex(3));

console.log(result);

4 Comments

ah once again Nina, your solutions are too elegant for my brain. What is going on in your fromIndex = i => _ => !i || !i--? what is that underscore? lodash? or something else?
lodash is just a not used variable. the underscore denoted that (as convention). maybe the more classical empty parameter list is better understandable, like: fromIndex = i => () => !i || !i--
ah, but why do we need either _ or ()?
because of the closure and filter needs a function.
1

the second argument in the filter callback is index. So You can do something like this

arr.filter((element,index) => index >= 3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.