'how to get last object from array and remains parent array same in javascript
Hi I have an array with a messages key which have multiple objects, i want to remove all objects except the last object in the messages array
I have example array below :
const array = [
{
messages: [
{ content: "abc", id: "message01" },
{ content: "def", id: "message02" },
{ content: "ghi", id: "message03" }
],
user: "user 1",
participants: ["user1", "user2"],
id: "chat01"
},
{
messages: [
{ content: "hello", id: "message01" },
{ content: "hi", id: "message02" },
{ content: "How are you", id: "message03" }
],
user: "user 2",
participants: ["user1", "user2"],
id: "chat02"
}
];
my excepted array below:
const expectedArray = [
{
messages: [{ content: "ghi", id: "message03" }],
user: "user 1",
participants: ["user1", "user2"],
id: "chat01"
},
{
messages: [{ content: "How are you", id: "message03" }],
user: "user 2",
participants: ["user1", "user2"],
id: "chat02"
}
];
Solution 1:[1]
const array = [
{
messages: [
{ content: "abc", id: "message01" },
{ content: "def", id: "message02" },
{ content: "ghi", id: "message03" }
],
user: "user 1",
participants: ["user1", "user2"],
id: "chat01"
},
{
messages: [
{ content: "hello", id: "message01" },
{ content: "hi", id: "message02" },
{ content: "How are you", id: "message03" }
],
user: "user 2",
participants: ["user1", "user2"],
id: "chat02"
}
];
for (let i = 0; i < array.length; i++) {
array[i].messages = new Array (array[i].messages[array[i].messages.length -1])
}
console.log (array)
Solution 2:[2]
const array = [
{
messages: [
{ content: "abc", id: "message01" },
{ content: "def", id: "message02" },
{ content: "ghi", id: "message03" }
],
user: "user 1",
participants: ["user1", "user2"],
id: "chat01"
},
{
messages: [
{ content: "hello", id: "message01" },
{ content: "hi", id: "message02" },
{ content: "How are you", id: "message03" }
],
user: "user 2",
participants: ["user1", "user2"],
id: "chat02"
}
];
/** slice() method gets the last element of the array.
If we provide negative index -1 to it
then it will remove the last item and
return it as a new array.
We overwrite messages array with the
return value of the slice() method which
is a new array containing only the last
element of the original messages array.
*/
array.forEach(e => e.messages = e.messages.slice(-1))
console.log(array)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Balint |
| Solution 2 | matzar |
