在我的问题中,我想用高阶函数替换我的for循环。
我需要创建一个函数,该函数接受一个数组作为参数,并返回一个数组,其中输入数组的值与x匹配,假设是10。
举个例子
const matchesValues = ( array ) => {
//MyFunc
}
console.log(matchesValues([2,8,5,5,6])) // [[2,8], [5,5]]以下是我目前所做的工作:
const matchesValues = (array) => {
if (array.length > 1) {
const matches = []
for (let i = array.length - 1; i >= 0; i--) {
if (i - 1 >= 0) {
if (array[i] + array[i - 1] == 10) {
matches.push([array[i - 1], array[i]])
}
}
}
return matches
}
}
console.log(matchesValues([2,8,5,5,5,6])) // expected : [2,8,5,5], recieved : [[5,5], [5,5], [2,8]]
请注意,顺序将保持不变,但这一点我可以处理。
您会用哪个高阶函数替换我的forloop?
非常感谢您的宝贵时间。
发布于 2020-12-01 20:58:31
使用reduce
const matchesValues = ( array ) => {
return array.reduce((previousValue, currentValue, currentIndex) => {
if (currentIndex === 0 || (array[currentIndex - 1] + currentValue) === 10) {
previousValue.push(currentValue);
}
return previousValue;
}, []);
};
console.log(matchesValues([2,8,5,5,5,6]));
发布于 2020-12-01 21:22:55
这里有一个更长的解决方案,但使用了您所要求的相同的return result format [[2,8], [5,5]]。当只有一个值匹配sum时,它也会处理这种情况,例如:10。
const matchValues = (array, valueToMatch) => {
const matchingValues = [];
if(!array.length) {
return matchingValues;
}
array.forEach((actualValue, index) => {
if((array.length-1) === index) {
if(actualValue === valueToMatch) {
matchingValues.push([actualValue]);
}
}
const clonedArray = array.filter((_, clonedValueIndex) => clonedValueIndex !== index);
clonedArray.forEach((value) => {
if((value + actualValue) === valueToMatch) {
let alreadyMatched = false;
if(matchingValues.length) {
matchingValues.forEach((matchingValue) => {
if(matchingValue.includes(value) && matchingValue.includes(actualValue) && (value + actualValue === valueToMatch)) {
alreadyMatched = true;
}
})
}
if(!alreadyMatched) {
matchingValues.push([actualValue, value]);
}
}
})
});
return matchingValues;
}
const returnedMatchingvalues = matchValues([2,8,5,5,5,6,10], 10);
console.log(returnedMatchingvalues); // [ [ 2, 8 ], [ 5, 5 ], [ 10 ] ]https://stackoverflow.com/questions/65090679
复制相似问题