Sum array of rational numbers and returning the result in simplest form in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of exactly two subarrays with two numbers each.

Both the subarrays represent a rational number in fractional form. Our function should add the rational numbers and return a new array of two numbers representing the simplest form of the added rational number.

Example

Following is the code −

 Live Demo

const arr = [
   [1, 2],
   [1, 3]
];
const findSum = (arr = []) => {
   const hcf = (a, b) => b ? hcf(b, a % b) : a;
   if(!arr.length){
      return null;
   };
   const [n, d] = arr.reduce(([a, x], [b, y]) => [a*y + b*x, x*y]);
   const g = hcf(n, d);
   return g === d ? n / d : [n / g, d / g];
};
console.log(findSum(arr));

Output

Following is the console output −

[5, 6]
raja
Published on 19-Apr-2021 08:16:09
Advertisements