Many of the other answers require multiple accesses to the initial array. The following types and deduplications at the same time. It is a little less accurate, but more impressive.
const inputArray = [5,3,23,24,5,7,3,2,5,10,24,2,31,31,31]; const getThirdGreatest = inputArray => { const sorted = [inputArray[0]]; // Add the first value from the input to sorted, for our for loop can be normalized. let migrated = false; let j; for(let i = 1; i<inputArray.length; i++) { // Start at 1 to skip the first value in the input array for(j=0; j<sorted.length; j++) { if(sorted[j] < inputArray[i]) { // If the input value is greater than that in the sorted array, add that value to the start of the sorted array sorted.splice(j,0,inputArray[i]); migrated = true; break; } else if(sorted[j] === inputArray[i]) { // If the input value is a duplicate, ignore it migrated = true; break; } } if(migrated === false) { // If the input value wasn't addressed in the loop, add it to the end of the sorted array. sorted[sorted.length] = inputArray[i]; } else { migrated = false; } } // Return the third greatest return sorted[2];; }; const start = performance.now(); getThirdGreatest(inputArray); // 23 const end = performance.now(); console.log('speed: ', end - start); // 0.1 - 0.2ms
source share