Jes*_*nke 2 javascript arrays underscore.js
我一直在尝试创建一个返回数组数组的通用分区函数。该函数应遵循以下准则:
参数:
目标:
为 <array> 中的每个元素调用 <function> 并传递参数:
element, key, <array>
Run Code Online (Sandbox Code Playgroud)返回一个由 2 个子数组组成的数组:
0. 包含 <function> 返回真值的所有值的数组
1. 包含 <function> 返回假值的所有值的数组
这是我到目前为止所拥有的。我得到两个回报。我觉得也许我只需要在两个不同的场合执行过滤功能,但我不知道如何将其组合在一起。高度赞赏您的想法和建议。
_.partition = function (collection, test){
var allValues = [];
var matches = [];
var misMatches = [];
_.filter(collection.value, function(value, key, collection){
if (test(value[key], key, collection) === "string"){
matches.push(value[key]);
}else{
misMatches.push(value[key]);
}
});
return allValues.push(matches, misMatches);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这是一个使用的版本reduce:
function partition(arr, filter) {
return arr.reduce(
(r, e, i, a) => {
r[filter(e, i, a) ? 0 : 1].push(e);
return r;
}, [[], []]);
}
Run Code Online (Sandbox Code Playgroud)
这是一个替代版本,用于Array#filter查找匹配项,并在运行过程中构建一个不匹配项的数组:
function partition(arr, filter) {
var fail = [];
var pass = arr.filter((e, i, a) => {
if (filter(e, i, a)) return true;
fail.push(e);
});
return [pass, fail];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5490 次 |
| 最近记录: |