代码之家  ›  专栏  ›  技术社区  ›  Raz Buchnik

如何将array.filter限制为10个结果?

  •  0
  • Raz Buchnik  · 技术社区  · 7 年前

    我有一个很大的数组,我想做一个自动完成的搜索,但我只想显示10个结果,所以在找到10个结果时停止遍历数组。我做了这个:

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

    但我不知道如何阻止 array.filter 当它达到所需的极限时。

    0 回复  |  直到 7 年前
        1
  •  4
  •   Icepickle    7 年前

    基本上,您可以使用生成器函数,它可以通过自制的限制来停止,如下面的函数

    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

    因此,当它达到maxSize作为参数时,它将停止,并且为了方便地将它返回到数组中,可以使用array.from,它将迭代生成器函数的迭代器

        2
  •  4
  •   adiga    7 年前

    您可以使用另一个变量来跟踪到目前为止匹配条件的项目数,并在达到限制后始终返回false。下面是一个例子:

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

    这里,我在用一个物体 {count: 0} 作为回调函数的上下文。你可以了解更多关于 Array.filter from here

        3
  •  4
  •   Nina Scholz    7 年前

    您可以交出一个计数器,并省略任何其他用于筛选的值。

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

    想到了冰泡菜 answer 在找到下一个有效项并生成此项的循环中稍提前一点。

    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));
        4
  •  2
  •   spender    7 年前

    I wrote a library 这样做很方便。

    下面是我如何找到以字符“1”开头的前100个数字

    const {blinq, range} = window.blinq;
    
    //create a large array of strings to search
    const arrToBeSearched = range(0,10000)
      .select(x => `${x}`)
      .toArray()
    
    const query = blinq(arrToBeSearched)
      .where(x => x.startsWith("1"))
      .takeWhile((x, i) => i < 100)
    
    const result = [...query] //no calculation until we materialize on this line
    
    console.log(result)
    <script src="https://cdn.jsdelivr.net/npm/blinq"></script>
        5
  •  1
  •   adiga    7 年前

    你不能 break Array.prototype.filter 方法。它将在每个元素上循环。你可以用一个简单的 for 找到10个项目时循环并断开

    const items = []
    for (const value of array) {
      if (value.includes(term))
        items.push(value)
      if (items.length === 10)
        break;
    }
    
        6
  •  1
  •   PopHip    7 年前

    只是为了骗局:

    编辑: 要澄清此代码,请选择列表中的前10个偶数

    let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
    
    const result = array.reduce((temp, value) => {
      if(value%2==0 && temp.length<10)
        temp.push(value);
      return temp;
    }, []);
    
    console.log(result);
        7
  •  0
  •   Maheer Ali    7 年前

    可以在上定义自定义方法 Array.prototype 这需要两个论点。结果数组将包含的回调和max元素。

    下面的代码从数组中获取前3个奇数。

    function filterUpto(callback,max){
      let len = this.length
      let res = [];
      let i = 0;
      while(res.length < max && i < len){
        if(callback(this[i],i,this)) res.push(arr[i])
        i++
      }
      return res;
    }
    
    Object.defineProperty(Array.prototype,'filterUpto',{
      value:filterUpto
    })
    
    let arr = [1,2,3,4,5,6,7,8,9,10];
    console.log(arr.filterUpto(x => x % 2,3)); //first three odd numbers
        8
  •  -1
  •   sarvon ks    7 年前

    var data = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14"]
    
    var limited = data.filter((val,i)=>i<10)
    console.log(limited)
        9
  •  -1
  •   Rajan Kumar    7 年前

    你只需简单地添加 .Slice(0,NO_OF_ELE_WANT) 找到前两个甚至没有

    [1,2,3,4,5,6,7,8,9,10].filter((e)=> e%2==0).slice(0,2)
    

    回答: let items = array.filter(r => r.indexOf(term)!=-1).slice(0,10);