简体   繁体   English

过滤,直到第一次满足某些条件

[英]filter until some condition is met for the first time

It's not a real world example, I over-simplified it. 这不是一个真实世界的例子,我过度简化了它。 Giving this array: 给这个数组:

const a = [1,2,3,4,5,6,7,8,4,5]; // Etc. Random numbers after.

I want to filter it to have only those matching a pattern (let's say greater than 3 for this trivial example) until something appends for the first time (let's say element is greater than 7) 我想过滤它只有那些匹配一个模式(比如说这个简单的例子大于3),直到第一次追加(比方说元素大于7)

So for this example, I just want: [4,5,6,7] . 所以对于这个例子,我只想要: [4,5,6,7] But with filter , I would have the trailing 4 and 5 : 但是使用filter ,我会得到尾随的45

const a = [1,2,3,4,5,6,7,8,4,5].filter((v) => v > 3)
// returns: [4, 5, 6, 7, 8, 4, 5]

So I want to get item from an array and definitively stop after a condition. 所以我想从一个数组中获取项目并在一个条件后最终停止。 How can I filter then stop after the first time a condition is not met? 如何在第一次不满足条件后过滤然后停止? (without for loop, I want to keep it "functional-like") (没有for循环,我想保持它“功能性”)

const a = [1,2,3,4,5,6,7,8,4,5,1,2,976,-1].awsome_function();
// returns: [4, 5, 6, 7, 8] because it stopped after the first 8.

You could use Array#some and combine both conditions. 你可以使用Array#some并结合两个条件。

 var array = [1,2,3,4,5,6,7,8,4,5], result = []; array.some(a => (a > 3 && result.push(a), a > 7)); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

ES5 ES5

 var array = [1,2,3,4,5,6,7,8,4,5], result = []; array.some(function (a) { if (a > 3) { result.push(a); } return a > 7; }); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

If you want to keep the functional style you can use this : 如果您想保留功能样式,可以使用:

Array.prototype.filterUntil = function(predicate, stop){

  let shouldStop = false;

  return this.filter(function filter(value, index){
    if(stop(value)){
      shouldStop = true;
    }

    return shouldStop && predicate(value);
  });
}

In your case you can call it like this : 在你的情况下你可以像这样调用它:

data.filterUntil(value => value > 3, value => value < 7)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM