How to limit for 10 results the array.filter?

Basically you can use a generator function, which can be stopped by a self made limit, like in the below function

function *filter(array, condition, maxSize) {
  if (!maxSize || maxSize > array.length) {
    maxSize = array.length;
  }
  let count = 0;
  let i = 0;
  while ( count< maxSize && i < array.length ) {
    if (condition(array[i])) {
      yield array[i];
      count++;
    }
    i++;
  }
}

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log( Array.from( filter(array, i => i % 2 === 0, 2 ) ) ); // expect 2 & 4

So it will stop after it reaches maxSize as a parameter, and to easily return it into an array, you can use Array.from, which will iterate the iterator of the generator function


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


You could hand over a counter and omit any other values for filtering.

const
    filter = v => v % 2,
    filterMax = (fn, c) => x => c && fn(x) && c--,
    max = 3,
    array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    result = array.filter(filterMax(filter, max));

console.log(result);

Taking the idea of Icepickle's answer a bit ahead with a loop for finding the next valid item and yield this one.

function* filterMax(array, cb, count) {
    var i = 0;
    while (count) {
        while (i < array.length && !cb(array[i])) i++;
        if (i >= array.length) return;
        yield array[i++];
        count--;
    }
}

const
    filter = v => v % 2,
    max = 3,
    array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log(...filterMax(array, filter, max));

Tags:

Javascript