gpt4 book ai didi

javascript - 使用 reduce 在 Javascript 中构建过滤函数

转载 作者:行者123 更新时间:2023-11-29 21:35:42 25 4
gpt4 key购买 nike

在一次采访中我被问到了一个让我摸不着头脑的问题。与其花周末时间担心结果,我想尝试解决问题,但我想不通:

使用下面的 reduce 函数,构建一个以数组和测试函数为参数的过滤函数,并返回一个新数组,该数组已根据测试函数过滤了先前数组的元素。

使用 forEach 或类似的方法会很简单,但要求是使用此 reduce 函数:

function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++)
current = combine(current, array[i]);
return current;
}

所以

var myArray = [0, 1, 3, 5, 9];
console.log(filter(myArray,function(x){
return x > 2;
}));

会回来

[3,5,9]

我尝试了以下方法,但我收到了非法的返回声明,我什至不确定我是否走上了正确的道路。

function filter(array, test){
var giveArray = [];
if(reduce(array,function(current,start){
return test(current);
},false)){
giveArray.push(current);
}
}
return giveArray;
}

最佳答案

基本思想是使用传递给 reducecombine 函数作为过滤元素的方法。您的方法似乎暗示 reduce 应该返回一个 bool 值,但这不是它的用途。使用 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
}

关于javascript - 使用 reduce 在 Javascript 中构建过滤函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com