

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Checking for uniqueness in an array in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument. The function should return true if all the numbers in the array appear only once (i.e., all the numbers are unique), and false otherwise.
For example −
If the input array is −
const arr = [12, 45, 6, 34, 12, 57, 79, 4];
Then the output should be −
const output = false;
because the number 12 appears twice in the array.
Example
The code for this will be −
const arr = [12, 45, 6, 34, 12, 57, 79, 4]; const containsAllUnique = (arr = []) => { const { length: l } = arr; for(let i = 0; i < l; i++){ const el = arr[i]; const firstIndex = arr.indexOf(el); const lastIndex = arr.lastIndexOf(el); if(firstIndex !== lastIndex){ return false; }; }; return true; }; console.log(containsAllUnique(arr));
Output
And the output in the console will be −
false
- Related Questions & Answers
- Checking for uniqueness of a string in JavaScript
- Checking an array for palindromes - JavaScript
- JavaScript Array: Checking for multiple values
- Checking for vowels in array of numbers using JavaScript
- Checking for majority element in a sorted array in JavaScript
- Checking progressive array - JavaScript
- Checking for Fibonacci numbers in JavaScript
- Checking for coprime numbers in JavaScript
- Checking for ascending arrays in JavaScript
- Checking for straight lines in JavaScript
- Checking for convex polygon in JavaScript
- Checking for increasing triplet in JavaScript
- Checking for special numbers in JavaScript
- JavaScript - Checking for pandigital numbers
- Checking for overlapping times JavaScript
Advertisements