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

177
Views
How to group subsequent objects of an array in Javascript/Typescript

Consider this array of objects:

[
    {
        key1: "AAA",
        key2: "BBB"
    },
    {
        key1: "BBB",
        key2: "CCC"
    },
    {
        key1: "CCC",
        key2: "DDD"
    },
    {
        key1: "XXX",
        key2: "YYY"
    },
]

How does one write a concise function to group them, so that if the key1 of the next object is equal to the key2 of the previous, the subsequent objects will become one?

The desired output of the above example:

[
    {
        key1: "AAA",
        key2: "DDD"
    },
    {
        key1: "XXX",
        key2: "YYY"
    },
]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do this with reduce:

const input = [
    {
        key1: "AAA",
        key2: "BBB"
    },
    {
        key1: "BBB",
        key2: "CCC"
    },
    {
        key1: "CCC",
        key2: "DDD"
    },
    {
        key1: "XXX",
        key2: "YYY"
    },
]

const result = input.reduce( (acc,i) => {  
  const last = acc[acc.length-1];
  if(last === undefined || last.key2 != i.key1){
    acc.push({...i});      
  }
  else{
    acc[acc.length-1] = {...last, key2:i.key2};
  }
  return acc;
},[]);

console.log(result);

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!