lodash - Count duplicate and then remove them

前端 未结 3 550
抹茶落季
抹茶落季 2021-01-15 03:56

I am trying to use lodash to first count how many duplicates are in an array of objects and the remove the duplicate (keeping the counter).

The code I have so far se

3条回答
  •  别那么骄傲
    2021-01-15 04:38

    I would use groupBy() to group all items with the same ID into separate arrays, then only keep one from each individual array, setting qty to its length.

    const array = [
      {id: 1, name: "test"},
      {id: 2, name: "test 2"},
      {id: 3, name: "test 3"},
      {id: 4, name: "test 4"},
      {id: 1, name: "test "},
      {id: 2, name: "test 2"}
    ];
    
    const result = _(array).groupBy('id').values().map(
      (group) => ({...group[0], qty: group.length})
    );
    
    console.log(result);

    Edit Updated to make it shorter, and prevent mutating the original array elements.

提交回复
热议问题