簡體   English   中英

在思考如何解決我的問題時需要幫助

[英]Need help on thinking about how to solve my problem

我想用我的問題中的高階函數替換我的 for 循環。

我需要創建一個 function,它將一個數組作為參數並返回一個數組,其中輸入數組的值與 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?

非常感謝您的時間。

使用減少

 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]));

這里有一個更長的解決方案,但return result format與您要求的相同[[2,8], [5,5]] 它還處理只有 1 個值與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 ] ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM