JS reduce: object accumulator titles

Tags: , ,



I am experimenting with the reduce function at the moment and wondering if I can tailor the accumulator’s keys’ name to be a specific value?

For example, the below code returns {16 years of experience: … } but I would like the return results to be categorized like the below:

Results wanted in this format:

{ Over 10 years:
  16: {
    {name: "Company One", category: "Finance", start: 1981, end: 2003},
    {name: "Company Two", category: "Retail", start: 1992, end: 2008}

  },


  20: { 
  {name: "Company One", category: "Finance", start: 1981, end: 2003},
  {name: "Company Two", category: "Retail", start: 1992, end: 2008}
  }

  ...
} etc...


const companies = [
    {name: "Company One", category: "Finance", start: 1981, end: 2003},
    {name: "Company Two", category: "Retail", start: 1992, end: 2008},
    {name: "Company Three", category: "Auto", start: 1999, end: 2007},
    {name: "Company Four", category: "Retail", start: 1989, end: 2010},
    {name: "Company Five", category: "Technology", start: 2009, end: 2014},
    {name: "Company Six", category: "Finance", start: 1987, end: 2010},
    {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
    {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
    {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
  ];
  

const industryExeperience = (obj, keyStart, keyEnd)=>{
  return obj.reduce((exp, curObj)=>{
    let differences = curObj[keyEnd] - curObj[keyStart];
    console.log(differences)
    if(differences > 10){
      exp[differences + ' years of experience'] = curObj

    }
    return exp
  },{})
}

console.log(industryExeperience(companies, 'start', 'end'))



Answer

To group by years use the difference as keys and an array as values. Push or concat each item into existing array or add new one as needed

const companies = [
    {name: "Company One", category: "Finance", start: 1981, end: 2003},
    {name: "Company Two", category: "Retail", start: 1992, end: 2008},
    {name: "Company Three", category: "Auto", start: 1999, end: 2007},
    {name: "Company Four", category: "Retail", start: 1989, end: 2010},
    {name: "Company Five", category: "Technology", start: 2009, end: 2014},
    {name: "Company Six", category: "Finance", start: 1987, end: 2010},
    {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
    {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
    {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
  ];
  
const grouped = companies.reduce((a,c)=>{
    const diff = c.end - c.start;
    a[diff] = (a[diff] || []).concat(c)
    return a;
},{})

console.log(grouped)


Source: stackoverflow