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.