Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
Javascript Array Formatting - Repeating Data

I want to show the repeating building names as an array in the employee array below.

const employess = [
  {
    building_name: "A",
    name: "John"
  },
  {
    building_name: "B",
    name: "John"
  },
  {
    building_name: "A",
    name: "Doe"
  },
  {
    building_name: "c",
    name: "John"
  },
  {
    building_name: "B",
    name: "Doe"
  }, 
  {
    building_name: "C",
    name: "David"
  }
];

For example, I want to convert it to the following array format.

const employess = [
  {
    building_name: ["A", "B", "C"],
    name: "John"
  },
  {
    building_name: ["A", "B"],
    name: "Doe"
  },
  {
    building_name: ["C"],
    name: "David"
  }
]

Thank you very much in advance for your help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Taken from Merge JavaScript objects in array with same key

const employess = [{
    building_name: "A",
    name: "John"
  },
  {
    building_name: "B",
    name: "John"
  },
  {
    building_name: "A",
    name: "Doe"
  },
  {
    building_name: "c",
    name: "John"
  },
  {
    building_name: "B",
    name: "Doe"
  },
  {
    building_name: "C",
    name: "David"
  }
]

let output = []

employess.forEach(function(item) {
  var existing = output.filter(function(v, i) {
    return v.name == item.name;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].building_name = output[existingIndex].building_name.concat(item.building_name);
  } else {
    if (typeof item.building_name == 'string')
      item.building_name = [item.building_name];
    output.push(item);
  }
});

console.log(output)

about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!