# Finding smallest sum after making transformations in JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## Problem

We are required to write a JavaScript function that takes in an array of positive integers. We can transform its elements by running the following operation on them as many times as required −

if arr[i] > arr[j] then arr[i] = arr[i] - arr[j]

When no more transformations are possible, our function should return its sum.

## Example

Following is the code −

Live Demo

const arr = [6, 9, 21];
const smallestSum = (arr = []) => {
const equalNums = arr => arr.reduce((a, b) => {
return (a === b) ? a : NaN;
});
if(equalNums(arr)){
return arr.reduce((a, b) => {
return a + b;
});
}else{
const sorted = arr.sort((a, b) => {
return a-b;
});
const last = sorted[arr.length-1] - sorted
sorted.pop();
sorted.push(last);
return smallestSum(sorted);
};
};
console.log(smallestSum(arr));

## Output

Following is the console output −

9