August 2024
Intermediate to advanced
516 pages
11h 47m
English
What follows is another implementation of the hasDuplicateValue function that doesn’t rely on nested loops. It’s a bit clever, so let’s first look at how it works and then we’ll see if it’s any more efficient than our first implementation.
| | function hasDuplicateValue(array) { |
| | const existingNumbers = []; |
| | |
| | for (let i = 0; i < array.length; i += 1) { |
| | if (existingNumbers[array[i]] === 1) { |
| | return true; |
| | } else { |
| | existingNumbers[array[i]] = 1; |
| | } |
| | } |
| | |
| | return false; |
| | } |
Here’s what this function does. It creates an array called existingNumbers, which starts out empty.
Then we use a loop to check each number in the input array. As it encounters each number, it places an arbitrary value (we’ve chosen ...
Read now
Unlock full access