删除对象数组中连续的重复产品并在 JavaScript 中对它们的数量求和

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

该数组包含一个包含连续重复的产品的列表。我需要删除数组中连续的重复产品并对它们的数量求和。

在此对象列表中,我们有四个

(D)
值和两个
(U)
值。如果这些值重复且连续,我想删除上一个重复值中的上一个值和总数量。

let books = [
  { id: "1", type: "D", price: 25, qty: 27},// *
  { id: "2", type: "D", price: 22, qty: 75},// *
  { id: "3", type: "D", price: 21, qty: 19},// *
  { id: "4", type: "D", price: 19, qty: 62},

  { id: "5", type: "U", price: 23, qty: 19},
  { id: "6", type: "D", price: 20, qty: 22},

  { id: "7", type: "U", price: 25, qty: 14},// *
  { id: "8", type: "U", price: 29, qty: 14}
]

结果会是这样的:

[
  { id: "4", type: "D", price: 19, qty: 121},
  { id: "5", type: "U", price: 23, qty: 19},
  { id: "6", type: "D", price: 20, qty: 22},
  { id: "8", type: "U", price: 29, qty: 28}
]

提前谢谢您。

javascript arrays object
1个回答
0
投票
let books = [
  { id: "1", type: "D", price: 25, qty: 27},// *
  { id: "2", type: "D", price: 22, qty: 75},// *
  { id: "3", type: "D", price: 21, qty: 19},// *
  { id: "4", type: "D", price: 19, qty: 62},

  { id: "5", type: "U", price: 23, qty: 19},
  { id: "6", type: "D", price: 20, qty: 22},

  { id: "7", type: "U", price: 25, qty: 14},// *
  { id: "8", type: "U", price: 29, qty: 14}
]



let removeDubs = (arr) => {
      let btm = 0;
      let top = 1;
      let result = []
      while(top !== arr.length){
        if(arr[top].type !== arr[btm].type) result.push(arr[btm])
        if(top == arr.length -1){
          if(result[result.length - 1].type !== arr[top].type){
            result.push(arr[top])
          }
        }
        top++;
        btm++
      }
      console.log(result)
    }
    
    removeDubs(books)
© www.soinside.com 2019 - 2024. All rights reserved.