skip to Main Content

I have seen similar question in stackoverflow, by using reduce method like this post: Javascript – Group by one property of object in an array of objects.

but I would like to get back a result as array [], instead of an object {}.

Here is a example

Input:

[
  {
    "name": "ABC Equity",
    "category": "Equity"
  },
  {
    "name": "EBC Bonds",
    "category": "Bond"
  },
  {
    "name": "Corporate Bonds",
    "category": "Bond"
  },
  {
    "name": "Private Equity",
    "category": "Equity"
  },
  {
    "name": "Fixed abc",
    "category": "Fixed"
  }
]

Expected after regrouping:

[
  {
    label: 'Equity',
    options: [
      { value: 'ABC Equity', label: 'ABC Equity'},
      { value: 'Private Equity', label: 'Private Equity'},
    ],
  },
  {
    label: 'Bond',
    options: [
      { value: 'EBC Bonds', label: 'EBC Bonds'},
      { value: 'Corporate Bonds', label: 'Corporate Bonds' },
    ],
  },
   {
    label: 'Fixed',
    options: [
      { value: 'Fixed abc', label: 'Fixed abc'}
    ],
  },
]

2

Answers


  1. To convert the object created using a reduce, you need to take the values of the object after reducing.

    Note the use of nullish coalescing assignment operators ??=

    This code is O(n) (runs once over the input)

    const arr1 = [ 
      { "name": "ABC Equity",      "category": "Equity" },
      { "name": "EBC Bonds",       "category": "Bond"   },
      { "name": "Corporate Bonds", "category": "Bond"   },
      { "name": "Private Equity",  "category": "Equity" },
      { "name": "Fixed abc",       "category": "Fixed"  }
    ];
    
    const arr2 = Object.values(
      arr1.reduce((acc,{name,category}) => {
        acc[category] ??= {};
        acc[category].label = category;
        acc[category].options ??= [];
        acc[category].options.push({"value": name, "label": name});
        return acc;
      },{})
    );
    
    console.log(arr2);
    Login or Signup to reply.
  2. This should work:

    const input = [
      {
        "name": "ABC Equity",
        "category": "Equity"
      },
      {
        "name": "EBC Bonds",
        "category": "Bond"
      },
      {
        "name": "Corporate Bonds",
        "category": "Bond"
      },
      {
        "name": "Private Equity",
        "category": "Equity"
      },
      {
        "name": "Fixed abc",
        "category": "Fixed"
      }
    ]
    
    let grouped = input.reduce((arr, cur) => {
      let group = arr.find(i => i.label == cur.category)
      if (group) {
        group.options.push(cur)
      } else {
        arr.push({ label: cur.category, options: [cur] })
      }
      return arr
    }, [])
    
    console.log(grouped)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search