Find top two clothing sizes in the array I was recently asked this question in an interview. Here is the solution I came up with. Please let know if I could have done this differently or in a more efficient manner.

The question is as follows:


  Determine The Top Two Clothes Sizes In The Following Array

["XS","S","S","M","L","XL","XLL","XL","XL","M","M","M","XS","XS","XS","XS"]

  
  The solution should be [ 'XS', 'M' ] since XS occurs 5 times and M
  occurs 4 times.


function determineTopTwo(arr){
let map = {};
let resultArr = [];
let result = [];
for(let i = 0; i &lt; arr.length; i++){
    if(!map[arr[i]]){
        map[arr[i]]=1;
    }else{
        map[arr[i]]++;
    }
}

for(key in map){
    resultArr.push([map[key],key]);
}
let newArr = resultArr.sort((a,b)=&gt;{
    return a[0]-b[0];
});

result.push(newArr[newArr.length-1][1], newArr[newArr.length-2][1]);
return result;
}
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"1 there isn't really a need to store the value in newArr because resultArr is sorted.


let newArr = resultArr.sort((a,b)=&gt;{
    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