- 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

# Find the Sum of fractions - JavaScript

We have an array of arrays like this −

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

Note that while the array can have any number of elements, each subarray should strictly contain two numbers.

The two numbers in each subarray represents a fraction. For example, the fraction represented by the first subarray is 12/56, by the second is 3/45 and so on.

We are required to write a JavaScript function that takes in one such array and calculates the sum of fractions represented by all the subarrays. Calculate the sum in fraction form (i.e., without converting them to decimals). Return the sum as an array of two elements representing the resulting fraction.

## Example

Following is the code −

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

## Output

Following is the output in the console −

[ 1731, 140 ]

- Related Articles
- Find the equivalent fractions of $frac{1}{3}$
- The difference of two unit fractions is one third of their sum. Find ratio of the larger fraction to smaller fraction
- Function that finds the simplest form of summed fractions in JavaScript
- Explain the types of fractions.
- Find required sum pair with JavaScript
- How can we find equivalent fractions?
- Write the fractions. Are all these fractions equivalent?"
- Representation of fractions
- What are the types of fractions?
- How to find the sum of all elements of a given array in JavaScript?
- In addition of unlike fraction,we first find the LCM of the __________of the two fractions.
- Explain conversion of fractions.
- Write the fractions and pair up the equivalent fractions from each row."
- Calculating the sum of digits of factorial JavaScript
- Using Kadane’s algorithm to find maximum sum of subarray in JavaScript

Advertisements