0

I have an array of Objects that I am trying to group based on the title regex value.

Example array:

[
  {
    id: "1",
    title: "[GroupA] Example Title",
    date: "example date",
  },
  {
    id: "2",
    title: "[GroupA] Example Title",
    date: "example date",
  },
  {
    id: "3",
    title: "[GroupB] Example Title",
    date: "example date",
  },
  {
    id: "4",
    title: "[GroupC] Example Title",
    date: "example date",
  },
];

I am trying to group each object based on the title: "[Group]"

The following .replace() gives me the Group value

let titleValue = data.title.replace(/(^.*\[|\].*$)/g, "");

// result: GroupA, GroupA, GroupB, GroupC

How would I be able to group these object arrays under their titleValue

TIA

yush
  • 365
  • 9
  • 26
  • How do you want to group? It would be easy to answer if you could add result as a code also? – DecPK May 24 '21 at 00:37
  • Do you want the result as an object that contain `group name` array as properties and then add them under that array? – DecPK May 24 '21 at 00:38
  • hey @decpk correct that would be ideal. What are your thoughts? Apologies that I didn't include a desired output/result as I don't really know how to achieve it – yush May 24 '21 at 00:40
  • @Drew. This is not exactly a Duplicate question. It would be better to reopen this. – DecPK May 24 '21 at 00:42
  • https://jsfiddle.net/x9kmvgf4/ – DecPK May 24 '21 at 00:45
  • @decpk OP has the value they want to group by, and this question (in variations) has been asked/answered many times. If OP disagrees then they can edit/update their question explaining how it isn't a duplicate and vote/request to reopen it themselves. https://stackoverflow.com/help/reopen-questions – Drew Reese May 24 '21 at 00:45

1 Answers1

1

Assuming you want an object which has group names as the keys and an array of all the matching elements as the values:

const data = [
  {
    id: "1",
    title: "[GroupA] Example Title",
    date: "example date",
  },
  {
    id: "2",
    title: "[GroupA] Example Title",
    date: "example date",
  },
  {
    id: "3",
    title: "[GroupB] Example Title",
    date: "example date",
  },
  {
    id: "4",
    title: "[GroupC] Example Title",
    date: "example date",
  },
];


const groupedData = data.reduce((acc, cur) => {
  let titleValue = cur.title.replace(/(^.*\[|\].*$)/g, "");
  if(acc[titleValue]) {
    acc[titleValue].push(cur);
  } else {
    acc[titleValue] = [cur];
  }
  return acc;
}, {});


console.log(groupedData);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • Thats awesome, thank you kindly for your help – yush May 24 '21 at 00:45
  • You can create also a shorter version also `(acc[titleValue] = acc[titleValue] ?? []).push(cur);` – DecPK May 24 '21 at 00:46
  • 1
    @decpk Also `(acc[titleValue] ??= []).push(cur);` would be shorter. But I'd like to make it easier to understand and has better support :p – Hao Wu May 24 '21 at 00:51