I have a json where I need to reduce the items when they are of a type (isSender
).
I need to reduce them when they are occurring consecutively.
The data can change.
The data looks like this:
"messages": [
{ "content": ["Foo"], "isSender": true },
{ "content": ["Bar"], "isSender": true },
{ "content": ["Lorem"], "isSender": true },
{ "content": ["Ipsum"], "isSender": true },
{ "content": ["Dolor"], "isSender": false },
{ "content": ["Sit Amet"], "isSender": false },
{ "content": ["No"], "isSender": true }
]
I need the content to be an array of messages when the consecutive isSender
key is the same. The output should look like this:
"messages": [
{
"content": ["Foo", "Bar", "Lorem", "Ipsum"],
"isSender": true
},
{ "content": ["Dolor", "Sit amet"], "isSender": false },
{ "content": ["No"], "isSender": true }
]
So far I have tried looping through the message array and checking if next messages have the same isSender
key. However this does not work for more than 2 messages.
let deleteIndex = [];
for(let i = 0 ; i < messages.length - 1; i++) {
const currMs = messages[i];
const nextMs = messages[i + 1];
if (nextMs.isSender == currMs.isSender) {
currMs.content.push(nextMs)
deleteIndex.push(i + 1) // saving index to be deleted once for loop is done
}
}
Can someone give me a clue on how to work around this?
Thanks in advance.
2
Answers
you can try this
json output
Use
reduce()
, on each iteration, we check if the last element in the result array has the sameisSender
value as the current object we’re dealing with.So,
if
we already have something in the final array (p.length
) AND the lastisSender
(p.at(-1).isSender
) has the same value as the currentisSender
(c.isSender
), append to thatcontent
listOtherwise, add the entry, which is just the current object itself (
return [ ...p, c ]
)Should you not like the
push
way, we can useObject.assign
to alter the index itself:Javascript spread on array index to 'push' new item to nested array