Friday, August 29, 2025
HomeLanguagesJavascriptReduce a fraction to its simplest form by using JavaScript

Reduce a fraction to its simplest form by using JavaScript

A fraction is simplified if there are no common factors (except 1) between the numerator and the denominator. For example, 4/6 is not simplified, since 4 and 6 both share 2 as a factor. If improper fractions can be transformed into integers. There are two possible ways to simplify the fraction by using JavaScript.  

The below examples will illustrate the approach:

Using math.js simplify() function: In this function, few rules are applied to the expression, you can create your own custom-made rules. Basically, this function is like a lambda function. Where you can make the rules according to your requirements 

Program: 

javaScript




// main function
function simplify(str) {
    var result = '', data = str.split('/'),
        numOne = Number(data[0]),
        numTwo = Number(data[1]);
    for (var i = Math.max(numOne, numTwo); i > 1; i--) {
    if ((numOne % i == 0) && (numTwo % i == 0)) {
        numOne /= i;
        numTwo /= i;
    }
    }
    if (numTwo === 1) {
    result = numOne.toString()
    } else {
    result = numOne.toString() + '/' + numTwo.toString()
    }
    return result
}
console.log(simplify("4/6"));
  
console.log(simplify(84810,985612));


Output:  

2/3
42405/492806

Using JavaScript _.reduce() function: The _.reduce() is an inbuilt function in JavaScript which is used to transform an array’s / object’s properties into one single value or is used to create a single result from a given list of values. When all the elements of the list are passed to the function/iterate and no more elements remain then the _.each loop ends. Here we will find the GCD of those numbers and dividing it by GCD we can make the output simpler. 

Program:  

Javascript




// Simplified fraction by finding the GCD and dividing by it.
function reduce(number,denomin){
var gcd = function gcd(a,b){
    return b ? gcd(b, a%b) : a;
};
gcd = gcd(number,denomin);
return [number/gcd, denomin/gcd];
}
  
console.log(reduce(15,20));
  
console.log(reduce(84810,985612));


Output:  

3,4
42405,492806
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32246 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6615 POSTS0 COMMENTS
Nicole Veronica
11787 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11835 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7011 POSTS0 COMMENTS
Thapelo Manthata
6685 POSTS0 COMMENTS
Umr Jansen
6699 POSTS0 COMMENTS