首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在思考如何解决我的问题时需要帮助

在思考如何解决我的问题时需要帮助
EN

Stack Overflow用户
提问于 2020-12-01 20:40:22
回答 2查看 46关注 0票数 0

在我的问题中,我想用高阶函数替换我的for循环。

我需要创建一个函数,该函数接受一个数组作为参数,并返回一个数组,其中输入数组的值与x匹配,假设是10。

举个例子

代码语言:javascript
复制
const matchesValues = ( array ) => {
    //MyFunc
} 
console.log(matchesValues([2,8,5,5,6])) // [[2,8], [5,5]]

以下是我目前所做的工作:

代码语言:javascript
复制
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?

非常感谢您的宝贵时间。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-01 20:58:31

使用reduce

代码语言:javascript
复制
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]));

票数 2
EN

Stack Overflow用户

发布于 2020-12-01 21:22:55

这里有一个更长的解决方案,但使用了您所要求的相同的return result format [[2,8], [5,5]]。当只有一个值匹配sum时,它也会处理这种情况,例如:10

代码语言:javascript
复制
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 ] ]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65090679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档