在 JavaScript/Node.js 中列出对象数组中的重复条目

offers我有一个包含如下对象的数组:


    sellItem: {

        id: _, 

        quantity: _

    }, 

    buyItem: {

        id: _, 

        quantity: _

    }, 

    volume: _

}

我想找到重复项 - 意思是具有相同“销售 ID”和“购买 ID”的报价。我还想在原始“优惠”数组中记录这些项目的索引。


我尝试这样做了 2 天,但没有成功,因为我发现很难用可管理的行数来写我想做的事情。StackOverflow 上的其他问题只涉及一个对象,而不是嵌套对象。


我的offers数组的示例:


{sellItem: {id: Pizza, quantity: 2}, buyItem: {id: Dollar, quantity: 1}, volume: 1}

{sellItem: {id: Pizza, quantity: 3}, buyItem: {id: Dollar, quantity: 2}, volume: 1}

{sellItem: {id: Banana, quantity: 2}, buyItem: {id: Pound, quantity: 1}, volume: 1}

{sellItem: {id: Apple, quantity: 2}, buyItem: {id: Euro, quantity: 1}, volume: 1}

{sellItem: {id: Pizza, quantity: 5}, buyItem: {id: Dollar, quantity: 3}, volume: 1}

这里的预期结果是:


0: Selling 2x Pizza for 1x Dollar

1: Selling 3x Pizza for 2x Dollar

4: Selling 5x Pizza for 3x Dollar

“优惠”数组中的所有其他条目都应忽略,因为它们不是重复的优惠。


慕盖茨4494581
浏览 122回答 1
1回答

四季花海

您可以使用filteralong withfind来搜索具有相同id.const arr = [{sellItem: {id: 'Pizza', quantity: 2}, buyItem: {id: 'Dollar', quantity: 1}, volume: 1},{sellItem: {id: 'Pizza', quantity: 3}, buyItem: {id: 'Dollar', quantity: 2}, volume: 1},{sellItem: {id: 'Banana', quantity: 2}, buyItem: {id: 'Pound', quantity: 1}, volume: 1},{sellItem: {id: 'Apple', quantity: 2}, buyItem: {id: 'Euro', quantity: 1}, volume: 1},{sellItem: {id: 'Pizza', quantity: 5}, buyItem: {id: 'Dollar', quantity: 3}, volume: 1}];const res = arr.filter(({sellItem: {id}},idx)=>   arr.find(({sellItem:{id:id2}},idx2) => idx !== idx2 && id === id2));console.log(res);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript