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

6
  • How do you want to group? It would be easy to answer if you could add result as a code also? Commented May 24, 2021 at 0:37
  • Do you want the result as an object that contain group name array as properties and then add them under that array? Commented May 24, 2021 at 0: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 Commented May 24, 2021 at 0:40
  • @Drew. This is not exactly a Duplicate question. It would be better to reopen this. Commented May 24, 2021 at 0:42
  • jsfiddle.net/x9kmvgf4 Commented May 24, 2021 at 0:45

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Thats awesome, thank you kindly for your help
You can create also a shorter version also (acc[titleValue] = acc[titleValue] ?? []).push(cur);
@decpk Also (acc[titleValue] ??= []).push(cur); would be shorter. But I'd like to make it easier to understand and has better support :p

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.