Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit for 10 results the array.filter?

Tags:

javascript

I have big array, I want to make an autocomplete search, but I want to display only 10 results, so stop iterating through the array by the time there were found 10 results. I have made this:

let items = array.filter(r => r.indexOf(term)!=-1);
console.log(items.length) // lots of items, need to be limited to 10

It works but I don't know how to stop the array.filter by the time it reaches the desired limit.

like image 975
Raz Buchnik Avatar asked May 16 '19 12:05

Raz Buchnik


People also ask

How do you set limits in an array?

To limit array size with JavaScript, we can use the array slice method. to define the add function that takes an array a and value x that we prepend to the returned array. We keep the returned array the same size as a by calling slice with 0 and a.

How do you filter numbers in an array?

Use the filter() method to filter an array to only numbers, e.g. arr. filter(value => typeof value === 'number') . The filter method returns an array with all the elements that satisfy the condition. In our case, all array elements with a type of number .

Is there a limit to an array?

The maximum length of an array is 4,294,967,295 - that is, the maximum unsigned 32-bit integer.


1 Answers

You could use another variable to keep track of how many items matched the condition so far and always return false after the limit has been reached. Here is an example:

const arr = [1,0,2,0,3,0,4,5,6,7,8,9,10,11,12,13,14];
const filtered = arr.filter(function(item) {
  if (this.count < 10 && item > 0) {
    this.count++;
    return true;
  }
  return false;
}, {count: 0});

console.log(filtered);

Here, I'm using an object {count: 0} as the context of the callback function. You can find out more about Array.filter from here

like image 64
Titus Avatar answered Sep 28 '22 01:09

Titus