kalyani_jamunkar
kalyani_jamunkar

Reputation: 610

How to grouped data based on category field in react js?

I want to group the data based on category field.

Input is:

var data: [
  {id:1, title:”title 1”, Category: “services”},
  {id:2 title:”title 2”, Category: “Blogs”},
  {id:3, title:”title 3”, Category: “services”},
  {id:4, title:”title 4”, Category: “services”},
  {id:5, title:”Services”, Category: “Blogs”}
]

Expected output is:

var out_data: {
     “services”:[
      {id: 1, title: ”title 1”},
      {id:3, title:”title 3”},
      {id:4, title:”title 4”}
    ],

  “Blogs”:[
       {id:2 title:”title 2”},
       {id:5, title:”Services”}
    ]
 }

Please provide any solution if you know. Thanks in advance.

Upvotes: 0

Views: 571

Answers (2)

Fcmam5
Fcmam5

Reputation: 6902

You can use Loadash's _.groupBy function:

npm i --save lodash.groupby

Example:

var groupBy = require('lodash.groupby');

var data = [
  { id: 1, title: 'title 1', Category: 'services' },
  { id: 2, title: 'title 2', Category: 'Blogs' },
  { id: 3, title: 'title 3', Category: 'services' },
  { id: 4, title: 'title 4', Category: 'services' },
  { id: 5, title: 'Services', Category: 'Blogs' }
]

var out_data = groupBy(data, 'Category');

console.log(out_data);

Will output:

{ services: 
   [ { id: 1, title: 'title 1', Category: 'services' },
     { id: 3, title: 'title 3', Category: 'services' },
     { id: 4, title: 'title 4', Category: 'services' } ],
  Blogs: 
   [ { id: 2, title: 'title 2', Category: 'Blogs' },
     { id: 5, title: 'Services', Category: 'Blogs' } ] }

Upvotes: 1

peetya
peetya

Reputation: 3618

Here is one from the thousands of solutions :)

var data = [
    {id:1, title:'title 1', Category: 'services'},
    {id:2, title:'title 2', Category: 'Blogs'},
    {id:3, title:'title 3', Category: 'services'},
    {id:4, title:'title 4', Category: 'services'},
    {id:5, title:'Services', Category: 'Blogs'},
];

var out_data = {};

data.forEach(function(row) {
    if (out_data[row.Category]) {
        out_data[row.Category].push(row);
    } else {
        out_data[row.Category] = [row];
    }
});

Upvotes: 1

Related Questions