lodash - 计算重复项,然后删除它们

Nic*_*ick 2 arrays object lodash

我正在尝试使用 lodash 首先计算对象数组中有多少重复项并删除重复项(保留计数器)。

到目前为止,我的代码似乎有效,但我不知道如何合并两者(抱歉,lodash 是新的)。

这是一些代码:

var 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"},
]

// This finds the duplicates and removes them
result = _.uniqBy(array, 'id')

// this counts how many duplicates are in the array
count = _(result)
.groupBy('id')
.map((items, name) => ({ name, count: items.length }))
.value();
Run Code Online (Sandbox Code Playgroud)

我想计数,然后删除但保留计数,以便最终结果基本上告诉我订单中有多少产品,但保持相同并将数量从1更改为2。

我确实尝试过这个,但它不起作用:

result = _(result)
  .groupBy('id')
  .map((items, name) => ({ name, count: items.length }))
  .uniqBy(result, 'name')
  .value()
Run Code Online (Sandbox Code Playgroud)

这会给我这样的东西:

result = [
{id: 1, name: "test", qty: 2},
{id: 2, name: "test 2", qty: 2},
{id: 3, name: "test 3", qty: 1},
{id: 4, name: "test 4", qty: 1}
]
Run Code Online (Sandbox Code Playgroud)

有什么帮助吗?

谢谢

Dav*_*oun 5

您正在寻找在原生 JS 中广泛使用的 reduce 函数。这是一个完整的代码示例,它在没有 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);
Run Code Online (Sandbox Code Playgroud)

这是思考这个问题的好方法:

1) 您是否希望输出数组的大小相同(例如 1:1,每个输入都有一个输出)?然后你会想要使用地图。

2)您是否希望输出数组的大小不同(通常更小)?然后你会想要使用reduce(或过滤器等)。

因为我们要删除重复项,所以您应该使用 #2。这至少会让你下次开始走正确的道路!