[英]filter until some condition is met for the first time
這不是一個真實世界的例子,我過度簡化了它。 給這個數組:
const a = [1,2,3,4,5,6,7,8,4,5]; // Etc. Random numbers after.
我想過濾它只有那些匹配一個模式(比如說這個簡單的例子大於3),直到第一次追加(比方說元素大於7)
所以對於這個例子,我只想要: [4,5,6,7]
。 但是使用filter
,我會得到尾隨的4
和5
:
const a = [1,2,3,4,5,6,7,8,4,5].filter((v) => v > 3)
// returns: [4, 5, 6, 7, 8, 4, 5]
所以我想從一個數組中獲取項目並在一個條件后最終停止。 如何在第一次不滿足條件后過濾然后停止? (沒有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.
你可以使用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
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; }
如果您想保留功能樣式,可以使用:
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);
});
}
在你的情況下你可以像這樣調用它:
data.filterUntil(value => value > 3, value => value < 7)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.