Skip to content
Advertisement

How to groupBy an Array of Objects and convert the duplicates

Hello to all i have this data structure that i need to group and if there are any duplicates to convert those two objects it in one line..

Data Structure

var shipTo = [
  { addressLine1: "address 1", name: "Jeff" },
  { addressLine1: "address 2", name: "Taylor" },
  { addressLine1: "address 1", name: "Megan" },
  { addressLine1: "address 3", name: "Madison" },
];

Grouped function

function groupArrayOfObjects(list, key) {
  return list.reduce(function (rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
}

I have groupedBy address attrube by this function above by address

const groupedAddress = groupArrayOfObjects(shipTo, "addressLine1");

My new data-structure is

enter image description here

My final Result wanna be like this :

Shipping Address for Shipment 1 & 3 is "address 1"

Shipping Address for Shipment 2 is "address 2"

Advertisement

Answer

reduce can take the index of the current array element as the 3rd parameter. you can then pass it to your accumulator and in the final array can do what you want with it

var shipTo = [
  { addressLine1: "address 1", name: "Jeff" },
  { addressLine1: "address 2", name: "Taylor" },
  { addressLine1: "address 1", name: "Megan" },
  { addressLine1: "address 3", name: "Madison" },
];

function groupArrayOfObjects(list, key) {
  return list.reduce(function (rv, x, idx) {
    (rv[x[key]] = rv[x[key]] || []).push({...x, index:idx+1});
    return rv;
  }, {});
}

const groupedAddress = groupArrayOfObjects(shipTo, "addressLine1");
console.log(groupedAddress)


//for completeness
Object.values(groupedAddress).forEach((address) => {
    let addressName = address[0].addressLine1
  let joinedIndices = address.map(({index}) => index).join(" & ")
  console.log(`Shipping Address for Shipment ${joinedIndices} is "${addressName}"`)
})
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement