lodash - Count duplicate and then remove them

前端 未结 3 557
抹茶落季
抹茶落季 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:35

    You're looking for a reduce function, which is widely available in native JS. Here's a full code sample that does the job without Lodash:

        const inputArray = [
            {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 uniqueArrayWithCounts = inputArray.reduce((accum, val) => {
            const dupeIndex = accum.findIndex(arrayItem => arrayItem.id === val.id);
    
            if (dupeIndex === -1) {
              // Not found, so initialize.
              accum.push({
                qty: 1,
                ...val
              });
            } else {
              // Found, so increment counter.
              accum[dupeIndex].qty++;
            }
            return accum;
        }, []);
    
        console.log(uniqueArrayWithCounts);

    Here's a good way to think about this:

    1) Do you want the output array to be the same size (e.g. 1:1, every input has an output)? Then you're going to want to use map.

    2) Do you want the output array to be a different size (usually smaller)? Then you're going to want to use reduce (or filter, etc).

    Because we want to remove duplicates, that should lead you to use #2. That'll at least get you started going down the right path next time!

提交回复
热议问题