簡體   English   中英

根據另一個布爾數組過濾數組

[英]Filtering an Array based on another Boolean array

假設我有兩個數組:

const data = [1, 2, 3, 4]
const predicateArray = [true, false, false, true]

我希望返回值是:

[1, 4]

到目前為止,我想出了:

pipe(
  zipWith((fst, scnd) => scnd ? fst : null)),
  reject(isNil) 
)(data, predicateArray)

是否有更清潔/內置的方法來做到這一點?

Ramda 中的解決方案是首選。

這適用於原生 JS (ES2016):

const results = data.filter((d, ind) => predicateArray[ind])

如果出於某種原因你真的想要一個 Ramda 解決方案,richsilv 的答案的一個變體很簡單:

R.addIndex(R.filter)((item, idx) => predicateArray[idx], data)

Ramda 沒有在其列表函數回調中包含index參數,這是有充分理由的,但addIndex插入它們。

正如所問,使用ramda.js

const data = [1, 2, 3, 4];
const predicateArray = [true, false, false, true];

R.addIndex(R.filter)(function(el, index) {
  return predicateArray[index];
}, data); //=> [2, 4]

更新示例以修復評論中引用的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM