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

140
Views
Group By Statuses using reduce

I have been using reduce() method to group by Open and Closes statuses (Status_111, Status_222, etc) which then creates an array of which Ids (item.Id) it is associated with.

Code is working and with an expected result but how do I avoid duplicated check when somewhat it does a similar thing and create blank arrays (Open and Close Status can have same Id (eg: Status_111), I am referring to this block section:

if (item.Open && !obj[item.Open]) {
    obj[item.Open] = {
      Open: [],
      Close: []
    }
}

if (item.Close && !obj[item.Close]) {
  obj[item.Close] = {
    Open: [],
    Close: []
  }
}

Usage:

const items = [
  { Id: 100, Open: 'Status_111', Close: 'Status_111' },
  { Id: 200, Open: 'Status_111', Close: 'Status_222' },
  { Id: 300, Open: 'Status_333', Close: 'Status_444' }
]

function groupByOpenAndClose(items) {
  return items.reduce(function (obj, item) {
    if (item.Open && !obj[item.Open]) {
        obj[item.Open] = {
          Open: [],
          Close: []
        }
    }

    if (item.Close && !obj[item.Close]) {
      obj[item.Close] = {
        Open: [],
        Close: []
      }
    }

    if (obj[item.Open]) {
      obj[item.Open].Open.push(item.Id)
    }

    if (obj[item.Close]) {
      obj[item.Close].Close.push(item.Id)
    }

    return obj
  }, {});
}

console.log(groupByOpenAndClose(items));

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

0

A reduce with a forEach is one way to get there

const items = [{
    Id: 100,
    Open: 'Status_111',
    Close: 'Status_111'
  },
  {
    Id: 200,
    Open: 'Status_111',
    Close: 'Status_222'
  },
  {
    Id: 300,
    Open: 'Status_333',
    Close: 'Status_444'
  }
]

let status = items.reduce((b, a) => {
  ['Open', 'Close'].forEach(s => {
    b[a[s]] = b[a[s]] || {Open: [], Close: []}
  });
  return b
}, {});

items.forEach(s => {
  status[s.Open].Open.push(s.Id);
  status[s.Close].Close.push(s.Id)
});

console.log(status)

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!