0

I have an array like ->

[{amount: 5000, date: "2020-04", user: "Bill Gates"}, {amount: 5000, date: "2020-04", user: "Jon Jones"}, {amount: 5000, date: "2020-05", user: "Jon Jones"}, {amount: 5000, date: "2020-05", user: "Bill Gates"}, ...]

And I want to modify it to ->

[{user: "Bill Gates", data: [{amount: 5000, date: "2020-04"}, {amount: 5000, date: "2020-05"}]}, {user: "Jon Jones", data: [{amount: 5000, date: "2020-04"}, {amount: 5000, date: "2020-05"}]}, ....]

I write reduce function ->

let reduced = array.reduce((sells, {user, date, amount}) => ({
    ...sells,
    user: user,
    data: [{date: date, amount: amount}],
}),{});

but it returns just one item of array. How can I return all of them?

2 Answers 2

2

You can search for the user using Array.prototype.find if found that means it is already processed and you can push the data object in the existing array else create a new object and insert it in the accumulator:

const data = [{amount: 5000, date: "2020-04", user: "Bill Gates"}, {amount: 5000, date: "2020-04", user: "Jon Jones"}, {amount: 5000, date: "2020-05", user: "Jon Jones"}, {amount: 5000, date: "2020-05", user: "Bill Gates"}];

const result = data.reduce((sells, {user, date, amount}) => {
   let match = sells.find(e => e.user === user);
   if(match){
      match.data.push({amount, date});
   }else{
      match = {user, data : [{amount, date}]};
      sells.push(match);
   }
   return sells;
}, []);
console.log(result);

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

Comments

1
input.reduce((acc, {user, amount, date}) => {
    const userToExtend = acc.find(u => u.user === user)
    if(userToExtend) userToExtend.data.push[{amount, date}]
    else acc.push({user, data: [{amount, date}]});
    return acc
}, []);

Comments

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.