Selecting Items in array - Javascript - Using Filter method - Stack Overflow

Someone asked a question today about figuring out to select certain elements within an array from I to

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

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.

Share Improve this question edited Apr 25, 2019 at 19:47 Sami Ahmed Siddiqui 2,3861 gold badge18 silver badges30 bronze badges asked Apr 25, 2019 at 19:40 mph85mph85 1,3564 gold badges21 silver badges44 bronze badges 1
  • appreciate that – mph85 Commented Apr 25, 2019 at 19:47
Add a ment  | 

4 Answers 4

Reset to default 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().

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

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

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744262372a4565698.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信