
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make 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 −
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
Advertisements