lodash-计算重复项,然后将其删除 [英] lodash - Count duplicate and then remove them

查看:349
本文介绍了lodash-计算重复项,然后将其删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

到目前为止,我的代码似乎有效,但是我无法弄清楚如何合并两者(对不起,lodash是新的).

The code I have so far seem to work, but I canìt figure out how to merge the two (sorry, new with 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();

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

I would like to count, then remove but keep the count, so that the final result basically tells me how many products are in the order, but keeping the same together and changing the quantity from 1 to 2.

我确实尝试过此方法,但不起作用:

I did try with this, but it doesn't work:

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

这会给我这样的东西:

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}
]

有帮助吗?

谢谢

推荐答案

我将使用groupBy()将具有相同ID的所有项目分组到单独的数组中,然后仅保留每个单独数组中的一项,将qty设置为其长度.

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);

<script src="https://unpkg.com/lodash@4.17.4/lodash.js"></script>

修改 已更新,使其更短,并防止突变原始数组元素.

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

这篇关于lodash-计算重复项,然后将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆