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