使用reduce在Javascript中构建过滤器函数
在一次面试中,有人向我提出了一个问题,这让我挠头。我本想尝试解决这个问题,但却无法解决,而不是整个周末都在担心结果: 使用下面的reduce函数,构建一个以数组和测试函数为参数的过滤器函数,并返回一个新数组,该数组已根据测试函数过滤了前一个数组的元素 使用forEach或类似工具会很简单,但要求使用此reduce功能:使用reduce在Javascript中构建过滤器函数,javascript,arrays,Javascript,Arrays,在一次面试中,有人向我提出了一个问题,这让我挠头。我本想尝试解决这个问题,但却无法解决,而不是整个周末都在担心结果: 使用下面的reduce函数,构建一个以数组和测试函数为参数的过滤器函数,并返回一个新数组,该数组已根据测试函数过滤了前一个数组的元素 使用forEach或类似工具会很简单,但要求使用此reduce功能: function reduce(array, combine, start) { var current = start; for (var i = 0; i <
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++)
current = combine(current, array[i]);
return current;
}
会回来吗
[3,5,9]
我尝试了下面的方法,但是我得到了一个非法的返回声明,我甚至不确定我走的是正确的道路
function filter(array, test){
var giveArray = [];
if(reduce(array,function(current,start){
return test(current);
},false)){
giveArray.push(current);
}
}
return giveArray;
}
基本思想是使用传递给
reduce
的combine
函数作为过滤元素的方法。您的方法似乎暗示reduce
应该返回一个布尔值,但这不是它的用途。使用test
进行条件检查,并使用reduce
将通过的元素填充数组
function filter(array, test) {
return reduce(array, function(arr, el) {
// Only add to the array if the test function is true
if (test(el)) {
arr.push(el);
}
// Always return the same array so you can keep filling it
return arr;
}, []); // Give it an empty array to start with
}
我已经看过好几次了:(由reduce addicts^^u撰写) 不允许使用<代码>函数足够大(x){返回x>2;}代码>/
var myArray=[0,1,3,5,9]
/console.log(myArray.filter(bigtough))
当然,您可以内联匿名,而不是声明bigtough函数。
function filter(array, test) {
return reduce(array, function(arr, el) {
// Only add to the array if the test function is true
if (test(el)) {
arr.push(el);
}
// Always return the same array so you can keep filling it
return arr;
}, []); // Give it an empty array to start with
}
function filter(array, test) {
return reduce(array, function(arr, el) {
// Only add to the array if the test function is true
if (test(el)) {
return [...current, el]
}
// Always return the same array so you can keep filling it
return [...current]
}, []); // Give it an empty array to start with
}