say we have fraction 2/4, it can be reduced to 1/2.
Is there a JavaScript function that can do the reducing?
Here is a recursive function using ECMAScript 6 reduce. It works for most fractions as long as the remainder isn't too small. 0 has been redefined to make it work for arrays like [1.2, 2.4, 12, 24]. I tested in Chrome and IE Edge so it may behave differently in other browsers or upgrades. So it should work with an array of floats.
Array.prototype.gcd = function () {
if (this.length === 0)
return null;
return this.reduce((prev, curr) => {
if (curr <= 1.00000000001e-12)
return prev
else
return [curr, prev % curr].gcd();
});
}
var reducedValueGCD = [1.2, 2.4, 12, 24, 240].gcd();
Search for MDN reduce or more info here.