|
| 1 | +// 43. Check if an Array Contains only Unique Values |
| 2 | + |
| 3 | +// Using of JavaScript Set |
| 4 | + |
| 5 | +{ |
| 6 | + function checkDistinct(array) { |
| 7 | + const checkSet = new Set(array); |
| 8 | + |
| 9 | + return checkSet.size === array.length; |
| 10 | + } |
| 11 | + // Input 1 |
| 12 | + const input1 = [7, 8, 1, 5, 9]; |
| 13 | + console.log(checkDistinct(input1)); |
| 14 | + |
| 15 | + // Input 2 |
| 16 | + const input2 = [7, 8, 1, 5, 5]; |
| 17 | + console.log(checkDistinct(input2)); |
| 18 | +} |
| 19 | + |
| 20 | +// Using of indexOf() Method |
| 21 | + |
| 22 | +{ |
| 23 | + function checkDistinct(array) { |
| 24 | + for (let i = 0; i < array.length; i++) { |
| 25 | + if (array.indexOf(array[i]) !== i) { |
| 26 | + return false; |
| 27 | + } |
| 28 | + } |
| 29 | + return true; |
| 30 | + } |
| 31 | + // Input1 |
| 32 | + const input1 = [7, 8, 1, 5, 9]; |
| 33 | + console.log(checkDistinct(input1)); |
| 34 | + |
| 35 | + //Input2 |
| 36 | + const input2 = [7, 8, 1, 5, 5]; |
| 37 | + console.log(checkDistinct(input2)); |
| 38 | +} |
| 39 | + |
| 40 | +// Using Array.filter() and Array.includes() |
| 41 | + |
| 42 | +{ |
| 43 | + function hasUniqueValues(arr) { |
| 44 | + return ( |
| 45 | + arr.filter((value, index, self) => self.indexOf(value) === index) |
| 46 | + .length === arr.length |
| 47 | + ); |
| 48 | + } |
| 49 | + console.log(hasUniqueValues([1, 2, 3, 4, 5])); // true |
| 50 | + console.log(hasUniqueValues([1, 2, 3, 4, 5, 6, 1])); // true |
| 51 | +} |
| 52 | + |
| 53 | +// Using Array.sort() and Array.every() |
| 54 | + |
| 55 | +{ |
| 56 | + function checkDistinct(array) { |
| 57 | + array.sort((a, b) => a - b); |
| 58 | + |
| 59 | + return array.every( |
| 60 | + (value, index) => index === 0 || value !== array[index - 1], |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + // Input 1 |
| 65 | + const input1 = [7, 8, 1, 5, 9]; |
| 66 | + console.log(checkDistinct(input1)); |
| 67 | + |
| 68 | + // Input 2 |
| 69 | + const input2 = [7, 8, 1, 5, 5]; |
| 70 | + console.log(checkDistinct(input2)); |
| 71 | +} |
| 72 | + |
| 73 | +// Using an object to track seen values |
| 74 | +{ |
| 75 | + function hasUniqueValues(arr) { |
| 76 | + let seen = {}; |
| 77 | + for (let val of arr) { |
| 78 | + if (seen[val]) { |
| 79 | + return false; |
| 80 | + } |
| 81 | + |
| 82 | + seen[val] = true; |
| 83 | + } |
| 84 | + |
| 85 | + return true; |
| 86 | + } |
| 87 | + |
| 88 | + console.log(hasUniqueValues([1, 2, 3, 4, 4])); |
| 89 | + console.log(hasUniqueValues([1, 2, 2, 4])); |
| 90 | +} |
0 commit comments