We'll learn how to get a subset of an array by specifying items to include with filter, or items to exclude using reject. We'll also look at how to get the results from both filter and reject, neatly separated with partition.
// we don't need to require in Plunker! //const R = require('ramda') const pets = [ {name: 'Spike', type: 'dog'}, {name: 'Mittens', type: 'cat'}, {name: 'Rover', type: 'dog'}, {name: 'Fluffy', type: 'cat'}, {name: 'Fido', type: 'dog'} ] const dogCheck = pet => pet.type == 'dog' // const result = R.filter(dogCheck, pets) // const result = R.reject(dogCheck, pets) const result = R.partition(dogCheck, pets) console.log(result) document.getElementById('output').innerHTML = `${JSON.stringify(result)}`
/* [
[{"name":"Spike","type":"dog"},{"name":"Rover","type":"dog"},
{"name":"Fido","type":"dog"}],
[{"name":"Mittens","type":"cat"},{"name":"Fluffy","type":"cat"}]
] */
本文通过实例演示了如何使用Ramda库中的filter、reject及partition方法来筛选数组元素。以宠物数组为例,展示了如何筛选出特定类型(如狗)的宠物,并将筛选与排除的结果分开呈现。
2192

被折叠的 条评论
为什么被折叠?



