- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum array of rational numbers and returning the result in simplest form in JavaScript
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 −
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]
Advertisements