0

I have an array list of objects, and I only want to return the last 7 objects in the array. help pls

I have tried to use, filter, map and find, but I could not get the output I was expecting

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
  })
}
adiga
  • 34,372
  • 9
  • 61
  • 83
  • 2
    Possible duplicate of [I want to print the last 'n' elements of an array](https://stackoverflow.com/questions/54293455/i-want-to-print-the-last-n-elements-of-an-array) and [Get the last two positions of an array](https://stackoverflow.com/questions/42368587) – adiga May 26 '19 at 14:56

3 Answers3

1

You could use Array#slice with a negative index from the end.

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

let lastSeven = welcomeMessage.slice(-7);

Scott Flodin
  • 320
  • 1
  • 5
  • Hi, Scott thanks for your response, but I am trying to implement this in nodjs. With a function so when l make a request like message/latest I will only return the last 6 messages in the arrry – Clement Irivbeguai May 27 '19 at 15:06
0

The above answers are correct and the best solution but if you need to use filter you can do something like this:

const items = welcomeMessage.filter((obj, index) => {
    const arrayLength = welcomeMessage.length;
    const wantedItems = 6;
    return arrayLength - index <= wantedItems;
});
Mwangi Njuguna
  • 75
  • 2
  • 10