Count unique elements in array without sorting

后端 未结 5 1845
醉梦人生
醉梦人生 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:58

    Why not something like:

    var arr = ["jam", "beef", "cream", "jam"]
    var uniqs = arr.reduce((acc, val) => {
      acc[val] = acc[val] === undefined ? 1 : acc[val] += 1;
      return acc;
    }, {});
    console.log(uniqs)

    Pure Javascript, runs in O(n). Doesn't consume much space either unless your number of unique values equals number of elements (all the elements are unique).

提交回复
热议问题