查詢分數和 - JavaScript


我們有一個這樣的陣列陣列 −

const arr = [[12, 56], [3, 45], [23, 2], [2, 6], [2, 8]];

請注意,雖然陣列可以包含任意數量的元素,但每個子陣列應嚴格包含兩個數。

每個子陣列中的兩個數表示一個分數。例如,第一個子陣列表示的分數為 12/56,第二個為 3/45,以此類推。

我們要求編寫一個 JavaScript 函式,該函式接受這樣一個數組,並計算所有子陣列表示的分數的和。以分數形式(即,不將其轉換為小數)計算和。將和作為表示結果分數的兩個元素的陣列返回。

舉例

以下是程式碼 −

const arr = [[12, 56], [3, 45], [23, 2], [2, 6], [2, 8]];
const gcd = (a, b) => {
   let num = 2, res = 1;
   while(num <= Math.min(a, b)){
      if(a % num === 0 && b % num === 0){
         res = num;
      };
      num++;
   };
   return res;
}
const sumFrac = (a, b) => {
   const aDenom = a[1], aNumer = a[0];
   const bDenom = b[1], bNumer = b[0];
   let resDenom = aDenom * bDenom;
   let resNumer = (aDenom*bNumer) + (bDenom*aNumer);
   const greatestDivisor = gcd(resDenom, resNumer);
   return [resNumer/greatestDivisor, resDenom/greatestDivisor];
};
const sumArrayOfFractions = arr => {
   return arr.reduce((acc, val) => sumFrac(acc, val));
};

輸出

以下是控制檯中的輸出 −

[ 1731, 140 ]

更新於: 16-Sep-2020

598 次瀏覽

啟動您的事業

完成課程以獲得認證

入門
廣告