• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

165
Views
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"

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error