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

问题描述 投票:0回答:2

我试图使用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();

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

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

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

有帮助吗?

谢谢

arrays object lodash
2个回答
1
投票

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

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>

编辑更新以使其更短,并防止改变原始数组元素。


2
投票

你正在寻找一个reduce函数,它在本机JS中广泛使用。这是一个没有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);

这是考虑这个的好方法:

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

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

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

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.