EN VI

remove consecutive duplicate products in an Array of object and sum their quantity in JavaScript?

2024-03-17 19:00:05
How to remove consecutive duplicate products in an Array of object and sum their quantity in JavaScript

The array contains a list with products that are consecutive duplicated. I need to remove the consecutive duplicate products in the array and sum their quantities.

In this list of objects we have four values of (D) and two values of (U). If the values are repeated and consecutive, I want to remove prev value and sum qty in last duplicate value.

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

The result will be like this:

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

and Thank you in advance.

Solution:

Reduce the array while looking ahead of 1 book and check whether it's of the same type as the current one. Sum qty accordingly.

Btw you have an error in your output, the first sum should be 183, you missed the last book in the series.

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

const result = books.reduce((r, book, i, arr) => {
  if(arr[i+1]?.type === book.type){
    r.qty += book.qty;
  } else {
    r.arr.push({...book, qty: r.qty + book.qty});
    r.qty = 0;
  }
  return r;
}, {arr:[],qty:0}).arr;

result.forEach(r=>console.log(JSON.stringify(r)));

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login