如何使用JavaScript创建一个分区函数。使用下列准则 [英] How to create a partition function in javascript. using the following guidelines
问题描述
我一直在试图创建一个返回数组的数组的通用功能分区。函数应该根据以下原则进行:结果
参数:
- 阵列
- 函数
目标:
-
呼叫及lt;作用>对于上述&lt每个元素;阵>传递给它的参数:
元素,钥匙,<阵列GT;
-
返回一个由2个子数组的数组:
  0。包含哪些&LT所有的值的数组;函数>返回的东西truthy结果
  1。包含哪些&LT所有的值的数组;函数>返回的东西falsy
下面是我迄今。我得到两个回报。我觉得也许我只是做在两个不同场合的过滤功能,但我不知道如何把它在一起。想法和建议具有很强的AP preciated。
_。分区=功能(收集,测试){
变种allValues = [];
变种匹配= [];
变种错配= [];
_.filter(collection.value,功能(价值,键,集合){
如果(测试(值[关键]键,集合)===字符串){
matches.push(值[关键]);
}其他{
misMatches.push(值[关键]);
}
});
返回allValues.push(匹配,不匹配);
}
下面是使用降低版本
:
功能分区(ARR,过滤器){
返回arr.reduce(
(R,E,I,A)=> {
- [R [过滤器(E,I,A)? 0:1] .push(E);
返回ř;
},[[],[]]);
}
下面是它使用阵列#过滤器
来找到比赛,并建立非匹配数组作为它会沿着另一种版本:
功能分区(ARR,过滤器){
VAR失败= []; VAR通= arr.filter((E,I,A)=> {
如果(过滤器(E,I,A))返回true;
fail.push(E);
}); 返回[及格,不及格]。
}
I've been trying to create a generic partition function that returns an array of arrays. the function should be made under the following guidelines:
Arguments:
- An array
- A function
Objectives:
Call <function> for each element in <array> passing it the arguments:
element, key, <array>
Return an array that is made up of 2 sub arrays:
0. An array that contains all the values for which <function> returned something truthy
1. An array that contains all the values for which <function> returned something falsy
Here is what I have so far. I get the return of two. I feel like maybe I just have to do the filter function on two separate occasions, but I'm not sure how to put it together. Thoughts and suggestions are highly appreciated.
_.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);
}
Here is a version which uses reduce
:
function partition(arr, filter) {
return arr.reduce(
(r, e, i, a) => {
r[filter(e, i, a) ? 0 : 1].push(e);
return r;
}, [[], []]);
}
Here's an alternative version which uses Array#filter
to find the matches, and builds an array of non-matches as it goes along:
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];
}
这篇关于如何使用JavaScript创建一个分区函数。使用下列准则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!