亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 JavaScript/Node.js 中列出對象數組中的重復條目

在 JavaScript/Node.js 中列出對象數組中的重復條目

慕蓋茨4494581 2022-12-22 15:15:17
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 Dollar1: Selling 3x Pizza for 2x Dollar4: Selling 5x Pizza for 3x Dollar“優惠”數組中的所有其他條目都應忽略,因為它們不是重復的優惠。
查看完整描述

1 回答

?
四季花海

TA貢獻1811條經驗 獲得超5個贊

您可以使用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);


查看完整回答
反對 回復 2022-12-22
  • 1 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號