Making array unique in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

A move consists of choosing any arr[i], and incrementing it by 1. Our function is supposed to return the least number of moves to make every value in the array arr unique.

For example, if the input to the function is −

const arr = [12, 15, 7, 15];

Then the output should be −

const output = 1;

Output Explanation

Because if we increment any 15 to 16, the array will consist of all unique elements.

Example

The code for this will be −

 Live Demo

const arr = [12, 15, 7, 15];
const makeUnique = (arr = []) => {
   arr.sort((a, b) => a - b);
   let count = 0;
   for (let i = 1; i < arr.length; i++) {
      if (arr[i] <= arr[i - 1]) {
         const temp = arr[i]
         arr[i] = arr[i - 1] + 1
         count += arr[i] - temp
      };
   };
   return count;
};
console.log(makeUnique(arr));

Output

And the output in the console will be −

1

Updated on: 09-Apr-2021

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements