How to count unique value from object of array in javascript

后端 未结 4 1217
-上瘾入骨i
-上瘾入骨i 2021-01-21 13:34

I want to calculate number of unique value and put that in new array. I have below array:

[
  { CategoryId: \"b5c3f43f941c\", CategoryName: \"Category 1\", Categ         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-21 13:57

    You can sort the array first then count the duplicates. The downside is it will modify the original yourArray due to being sorted, so use with caution.

    yourArray.sort((a, b) => {
      if (a.CategoryName > b.CategoryName) {
        return 1;
      }
      if (a.CategoryName < b.CategoryName) {
        return -1;
      }
      return 0;
    });
    
    var pivot = yourArray[0];
    pivot.count = 0;
    var counted = [pivot];
    yourArray.forEach(item => {
      if (item.CategoryId === pivot.CategoryId) {
        pivot.count++;
      } else {
        pivot = item;
        pivot.count = 1;
        counted.push(pivot);
      }
    });
    

提交回复
热议问题