// Make a javascript function that removes the "isSeen" property for every message object except the last one, of a sequence of messages in an array...
I've tried everything but kept getting bugs and errors... Here is an image of the UI that i want to reach...
// GOAL: make a javascript function that turns the messages array like this:
[{
isSeen: false, // before: it was true...
id: 1,
content: "Hello",
createdAt: new Date(),
user: {
name: "John Doe",
isOwner: false,
},
},
{
isSeen: false, // before: it was true...
id: 1,
content: "Do you know someone who can help?",
createdAt: new Date(),
user: {
name: "John Doe",
isOwner: false,
},
},
{
isSeen: true, // <-
id: 1,
content:
"Do you know someone who can help?",
createdAt: new Date(),
user: {
name: "John Doe",
isOwner: false,
},
},
{
isSeen: false,
id: 1,
content: "No BRO!",
createdAt: new Date(),
user: {
name: "Ramy Hadid",
isOwner: true,
},
},
{
isSeen: true, // Here, it's set to true because it's the last message sent by Ramy...
id: 1,
content:
"Stop asking me ridiculous questions, that's soo annoying, am starting to get annoyed of you, stop it!",
createdAt: new Date(),
user: {
name: "Ramy Hadid",
isOwner: true,
},
}]
function splitArrayByOwner(arr) {
const result = [];
let tempArr = [];
for (let i = 0; i < arr.length; i++) {
if (tempArr.length === 0) {
tempArr.push(arr[i]);
} else if (tempArr[0].isOwner === arr[i].isOwner) {
tempArr.push(arr[i]);
} else {
result.push(tempArr);
tempArr = [arr[i]];
}
}
if (tempArr.length > 0) {
result.push(tempArr);
}
return result;
}
function joinArraysByOwner(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(...arr[i]);
}
return result;
}
messages = joinArraysByOwner(
splitArrayByOwner(messages).map((sequence) => {
sequence = sequence.map((message) => {
message.isSeen = false;
return message;
});
sequence[sequence.length - 1].isSeen = true;
return sequence;
})
);
In case somebody wants it :)