Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

>Solution :

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}"`)
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading