Count unique elements in array without sorting

后端 未结 5 1860
醉梦人生
醉梦人生 2020-11-30 03:17

In JavaScript the following will find the number of elements in the array. Assuming there to be a minimum of one element in the array

arr = [\"jam\", \"beef\         


        
5条回答
  •  执念已碎
    2020-11-30 03:46

    This expression gives you all the unique elements in the array without mutating it:

    arr.filter(function(v,i) { return i==arr.lastIndexOf(v); })
    

    You can chain it with this expression to build your string of results without sorting:

    .forEach(function(v) {
         results+=v+" --> " + arr.filter(function(w){return w==v;}).length + " times\n";
    });
    

    In the first case the filter takes only includes the last of each specific element; in the second case the filter includes all the elements of that type, and .length gives the count.

提交回复
热议问题