【问题标题】:Stop filtering the array if the condition is not met at the next index even though there is still data that can satisfy the next index如果在下一个索引处不满足条件,则停止过滤数组,即使仍有数据可以满足下一个索引
【发布时间】:2022-01-07 09:15:37
【问题描述】:

我想知道如何从过滤结果中检索数据,如果过滤时在下一个索引中不满足条件,则过滤过程会自动停止。这是我制作的代码示例

var array = [1,2,3,4,5,100, 12,13,14]
var filterArr = array.filter((value, index) => {
   var nextValue = array[index+1]
   if(value >= 20 && nextValue <= 20){
     return true 
   }
   return false
})
//result that i want in filterArr variable is [1,2,3,4,5]

而我想要的结果就是这样,忽略值11、12、13、14,因为在下一个索引中有一个值是100,它大于20

【问题讨论】:

  • 能否请您具体说明您要过滤的内容?

标签: javascript arrays reactjs


【解决方案1】:

您可以将.slice().findIndex() 一起使用,而不是使用.filter()。首先,您可以使用.findIndex() 找到100 元素的索引,然后使用.slice() 您可以将所有元素保持在该索引之前但不包括该索引:

const array = [1, 2, 3, 4, 5, 100, 12, 13, 14];
const idx = array.findIndex((value, i) => value >= 20 && array[i+1] <= 20);
const res = idx > -1 ? array.slice(0, idx) : array.slice(); // res is a copy of the array, potentially with some items removed
console.log(res);

【讨论】:

    【解决方案2】:

    如果 flag 是 false,您可以在闭包中获取一个标志并从过滤中省略下一个值。

    const
        array = [1, 2, 3, 4, 5, 100, 12, 13, 14],
        result = array.filter(
            (flag => value => flag && (flag = value <= 20))
            (true)
        );
        
    console.log(result); // [1, 2, 3, 4, 5]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多