我有一个对象数组列表,我只想返回数组中的最后7个对象。帮助请
我尝试使用,过滤,映射和查找,但无法获得预期的输出结果
var welcomeMessage = [{
from: "Clement",
text: "Welcome to Freeborn chat system!",
id: 0
},
{
from: "mark",
text: "Hello",
id: 1
},
{
from: "clement",
text: "welcome",
id: 2
},
{
from: "mark",
text: "long time",
id: 3
},
{
from: "clement",
text: "yeah, indeed",
id: 4
},
{
from: "mark",
text: "real good to be hear",
id: 5
},
{
from: "clement",
text: "you looking good",
id: 7
},
{
from: "mark",
text: "Hello",
id: 8
},
{
from: "clement",
text: "welcome",
id: 9
}
]
const messages = [welcomeMessage]
function latestMessage(messages, search) {
let search = rquest.body;
let messages = messages.length - 7
const messages.filter(message => {
return message
})
}
答案 0 :(得分:1)
您可以将Array#slice
与结尾处的负索引一起使用。
var welcomeMessage = [{ from: "Clement", text: "Welcome to Freeborn chat system!", id: 0 }, { from: "mark", text: "Hello", id: 1 }, { from: "clement", text: "welcome", id: 2 }, { from: "mark", text: "long time", id: 3 }, { from: "clement", text: "yeah, indeed", id: 4 }, { from: "mark", text: "real good to be hear", id: 5 }, { from: "clement", text: "you looking good", id: 7 }, { from: "mark", text: "Hello", id: 8 }, { from: "clement", text: "welcome", id: 9 }, { from: "mark", text: "long time", id: 10 }, { from: "clement", text: "yeah, indeed", id: 11 }];
console.log(welcomeMessage.slice(-6));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
让lastSeven = welcomeMessage.slice(-7);
答案 2 :(得分:0)
以上答案是正确的,也是最佳解决方案,但是如果您需要使用过滤器,则可以执行以下操作:
const items = welcomeMessage.filter((obj, index) => {
const arrayLength = welcomeMessage.length;
const wantedItems = 6;
return arrayLength - index <= wantedItems;
});