0

I pass an array and an id to a function, this function will group that array by id.

id = "f58d5d3a6c4"; // id is read-only
array = [
    {createOn: "2021-02-06T18:03:13.915", message: "Hello Subscriber"},
    {createOn: "2021-02-06T18:03:42.462", message: "New Messages"},
    {createOn: "2021-01-29T14:21:01.761", message: "Hello"},
    {createOn: "2021-02-06T18:02:56.145", message: "Hello Subscriber"}
]

I want to group the above array like so:

"f58d5d3a6c4": [
    {createOn: "2021-02-06T18:03:13.915", message: "Hello Subscriber"},
    {createOn: "2021-02-06T18:03:42.462", message: "New Messages"},
    {createOn: "2021-01-29T14:21:01.761", message: "Hello"},
    {createOn: "2021-02-06T18:02:56.145", message: "Hello Subscriber"}
]

This is my code, but I just get an empty array after console.log it out:

const group = array.reduce((r, a) => {
    var key = id;
    key = [...(r || []), a];
    return r;
}, []);

Can you help me how to fix that? Thank you.

1 Answer 1

1

Complicated, why not just

id = "f58d5d3a6c4"; // id is read-only
array = [
    {createOn: "2021-02-06T18:03:13.915", message: "Hello Subscriber"},
    {createOn: "2021-02-06T18:03:42.462", message: "New Messages"},
    {createOn: "2021-01-29T14:21:01.761", message: "Hello"},
    {createOn: "2021-02-06T18:02:56.145", message: "Hello Subscriber"}
]


const newObj = {
  [id]: array
};
console.log(newObj);

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

3 Comments

Oh. Perhaps I thought it was too complicated. :)) Thank you
But what if I want to return an array? like ["f58d5d3a6c4": [....]]
That syntax is not valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.