为了账号安全,请及时绑定邮箱和手机立即绑定

如何在给定数组中仅添加具有相同 _id 的 sumdigit 列值

如何在给定数组中仅添加具有相同 _id 的 sumdigit 列值

翻翻过去那场雪 2022-12-02 16:45:20
输入数组=>[{_id: "555", sumdigit: 1000,  Price: 1000}{_id: "677", sumdigit: 10,  Price: 320} {_id: "555", sumdigit: 170, Price: 1000}  {_id: "444", sumdigit: 10,  Price: 1000} {_id: "400", sumdigit: 10,  Price: 320}]输出数组=>[{_id: "555", sumdigit: 1170,  Price: 1000},{_id: "677", sumdigit: 10,  Price: 320},{_id: "444", sumdigit: 10,  Price: 1000}, {_id: "400", sumdigit: 10,  Price: 320}]
查看完整描述

3 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

这是你想要的:


const a = [{ _id: "555", sumdigit: 1000, Price: 1000 }, { _id: "677", sumdigit: 10, Price: 320 }, { _id: "555", sumdigit: 170, Price: 1000 }, { _id: "444", sumdigit: 10, Price: 1000 }, { _id: "400", sumdigit: 10, Price: 320 }];


console.log([...a.reduce((a, c) => {

    if (a.has(c._id)) {

        a.get(c._id).sumdigit += c.sumdigit;

    } else {

        a.set(c._id, c);

    }

    return a;

}, new Map()).values()])


查看完整回答
反对 回复 2022-12-02
?
动漫人物

TA贡献1815条经验 获得超10个赞

您可以使用 reduce 来累积值


const arrays=[{_id: "555", sumdigit: 1000,  Price: 1000}, {_id: "677", sumdigit: 10,  Price: 320} , {_id: "555", sumdigit: 170, Price: 1000} , {_id: "444", sumdigit: 10,  Price: 1000} , {_id: "400", sumdigit: 10,  Price: 320}]


 res=arrays.reduce((acc,{_id,sumdigit,Price}) => {

   if(!acc[_id]) acc[_id] = {...acc[_id],_id,sumdigit,Price}

   else acc[_id] = {...acc[_id],_id:_id,

                   sumdigit : acc[_id].sumdigit + sumdigit,Price:Price}

   return acc

 },{})

 console.log(Object.values(res))


查看完整回答
反对 回复 2022-12-02
?
当年话下

TA贡献1890条经验 获得超9个赞

您可以通过迭代input array检查 _id 是否在输出中以增加sumdigit属性来创建输出。


试试这段代码。


const input = [

  {_id: "555", sumdigit: 1000,  Price: 1000},

  {_id: "677", sumdigit: 10,  Price: 320},

  {_id: "555", sumdigit: 170, Price: 1000},

  {_id: "444", sumdigit: 10,  Price: 1000},

  {_id: "400", sumdigit: 10,  Price: 320},

]



const output = [];


// Iterate over the input array

for (let i = 0; i < input.length; i++) {

  const element = input[i];


  // Check if the id is already present in the output variable

  const prevObjectIdx = output.findIndex(obj => obj._id === element._id);


  /**

   * If the id is already into the output array just increase the subdigit with the other one.

   * Otherwise, just add the element into the output variable.

   */

  if (prevObjectIdx !== -1) {

    output[prevObjectIdx].sumdigit += element.sumdigit;

  } else {

    output.push(element);

  }

};



console.log(output)


查看完整回答
反对 回复 2022-12-02
  • 3 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信