In one of my projects there is a need to remove objects from on object array if the type property of those objects is the same and there are more than 2 consecutive objects with the same type in the array.
For example:
[
{
type: 'joined',
name: 'test',
},
{
type: 'joined',
name: 'test 1',
},
{
type: 'left',
name: 'test 2',
},
{
type: 'joined',
name: 'test 3',
},
{
type: 'joined',
name: 'test 4',
},
{
type: 'joined',
name: 'test 5',
},
{
type: 'joined',
name: 'test 6',
},
{
type: 'joined',
name: 'test 7',
}
]
Should result in:
[
{
type: 'joined',
name: 'test',
},
{
type: 'joined',
name: 'test 1',
},
{
type: 'left',
name: 'test 2',
}
]
So, the first 2 objects had the "joined" type but there are not more than 2 consecutive objects with that same type so they did not get removed. But the last 5 were removed as they all had the same type and there were more than 2 consecutive objects with that same type.
And the removed items should be collected into a separate array.
From Group same elements in JS array, but only when consecutive I have the following snippet:
const messages = [
{ message: "One", user: "Bob" },
{ message: "Two", user: "Bob" },
{ message: "Three", user: "Bob" },
{ message: "Hello", user: "Sam" },
{ message: "Hello", user: "Bob" },
{ message: "Hello", user: "Sam" },
{ message: "Hello", user: "Sam" }
]
let currentUser;
let groupedMessages = [];
for (message of messages) {
if (message.user !== currentUser) {
groupedMessages.push([]);
currentUser = message.user;
}
groupedMessages[groupedMessages.length - 1].push(message)
}
console.log(groupedMessages);
However it doesn't take into account the minimum threshold which is 2. Can anybody point me in the right direction as to how this can be modified to suit my needs?