You didn't specify if you were allowed to use ecmascript-6 features or not but presumably you were, since you used let
and arrow functions. As an interviewer, I would note that you used those features, yet you iterated over the array using a regular for
loop instead of using for...of
. That isn't necessarily a bad thing since it demonstrates that you know how to increment a counter in a standard loop and then use that for indexing into the array, but you don't have to if you use a for...of
loop.
The technique for sorting the array is good, though because Array.prototype.sort()
"sorts the elements of an array in place and returns the array""sorts the elements of an array in place and returns the array"1 there isn't really a need to store the value in newArr
because resultArr
is sorted.
let newArr = resultArr.sort((a,b)=>{
return a[0]-b[0];
});
You could have just returned the first two elements of resultArr
.
Also, const
could have been used for any variable that is never re-assigned - including arrays that merely have elements pushed into them - to avoid accidental re-assignment.
1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort