mph85
mph85

Reputation: 1356

Selecting Items in array - Javascript - Using Filter method

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.

Upvotes: 0

Views: 4565

Answers (4)

kesavi
kesavi

Reputation: 59

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

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

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);

Upvotes: 1

jdagosta
jdagosta

Reputation: 19

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

Upvotes: 1

Pointy
Pointy

Reputation: 413826

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

Upvotes: 5

Related Questions