0

I want to combine same key element in below object and new array as output.

    const items = [
    {status:'all',task:'AA'},
    {status:'all',task:'BB'},
    {status:'working',task:'XX'},
    {status:'working',task:'YY'},
    {status:'complete',task:'ZZ'},
]

In items, I want to combine same status and make new array like below.

    const newItems = [
    {status:'all',task:['AA','BB']},
    {status:'working',task:['XX','YY']},
    {status:'complete',task:['ZZ']},
]

So I tried to make code below.

    let baseItems = items
const newItems = baseItems.map((e)=>{
    const newBaseItems = baseItems.filter((v)=>v.status === e.status)
    newBaseItems.map((e)=>{
        return {
            status:e.status,
            task:e.task
        }
    })        
})
console.log(newItems)

but out was like [undefined,undefined,,,,] Does anyone teach me, please?

1
  • At the very least you'll need to return newBaseItems in the first map Commented Mar 1, 2021 at 1:53

1 Answer 1

2

I don't think a nested loop is the right approach here. Iterate just once, into an object indexed by status. On each iteration, create a { status, task: [] } on the object if it doesn't exist yet, then push to the task array:

const items = [
    {status:'all',task:'AA'},
    {status:'all',task:'BB'},
    {status:'working',task:'XX'},
    {status:'working',task:'YY'},
    {status:'complete',task:'ZZ'},
];

const itemsByStatus = {};
for (const { status, task } of items) {
  itemsByStatus[status] ??= { status, task: [] };
  itemsByStatus[status].task.push(task);
}
console.log(Object.values(itemsByStatus));

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

4 Comments

Thank you for your answer! I really appreciate it. Thank kind of code is magic for me. Can I ask some for your code? itemsByStatus[status] ??= { status, task: [] }; I never seen "??" . What meaning in your code?
Nullish assignment developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Here, equivalent to if (!itemsByStatus[status]) itemsByStatus[status] = which is a lot more verbose
Thanks for your answer! So if I rewrite use if statement, like below? for (const { status, task } of items) { if (!itemsByStatus[status]) { itemsByStatus[status] = { status, task: [] }; itemsByStatus[status].task.push(task); } console.log(Object.values(itemsByStatus)); }
Yes, you can do that instead, it'll have the same result in the end

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.