- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Articles
- Summing up unique array values in JavaScript
- Finding unique string in an array in JavaScript
- Counting unique elements in an array in JavaScript
- Making an existing field Unique in MySQL?
- Count unique elements in array without sorting JavaScript
- Constructing array from string unique characters in JavaScript
- Filter unique array values and sum in JavaScript
- Finding first unique element in sorted array in JavaScript
- Extract unique values from an array - JavaScript
- Get unique item from two different array in JavaScript
- Detecting the first non-unique element in array in JavaScript
- Unique pairs in array that forms palindrome words in JavaScript
- Finding the sum of unique array values - JavaScript
- How to get all unique values in a JavaScript array?
- Unique sort (removing duplicates and sorting an array) in JavaScript

Advertisements