- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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]
- Related Articles
- Returning array of natural numbers between a range in JavaScript
- Returning the expanded form of a number in JavaScript
- Returning the value of (count of positive / sum of negatives) for an array in JavaScript
- Returning an array containing last n even numbers from input array in JavaScript
- Taking the absolute sum of Array of Numbers in JavaScript
- Converting array of Numbers to cumulative sum array in JavaScript
- Function that finds the simplest form of summed fractions in JavaScript
- Returning just greater array in JavaScript
- Squared and square rooted sum of numbers of an array in JavaScript
- Sum of all prime numbers in an array - JavaScript
- Accessing and returning nested array value - JavaScript?
- Returning the highest value from an array in JavaScript
- Simplest code for array intersection in JavaScript?
- Non-composite numbers sum in an array in JavaScript
- Returning reverse array of integers using JavaScript

Advertisements