Qzen
Qzen

Reputation: 23

Make array hold 10 latest entries

I am trying to get a array to hold the 10 latest values, so far it cant get it to work.

var messages = new Array(10);

function addmessage(message) {
    messages.unshift(message);
    messages.length = 10;
}

But when i try to show the array i cant get it to show the messages in order...

And i display the array with

$.each(messages, function(key, value) {
    if(value != null) {
        $("#messages").append(value + "<br>");
    }
});

Upvotes: 1

Views: 198

Answers (4)

Joseph
Joseph

Reputation: 119847

var messages = []; //use an array literal instead.

function addmessage(message) {  

    //unshift loads the new value into the beginning
    messages.unshift(message);

    //if you want to place it in the end, you can use push()
    //messages.push(message);

    //if you really want it to remain 10,  pop off the last
    if(messages.length > 10){
        messages.pop();
        //and if push()
        //messages.shift()
    }              
}

//loop through and append, "latest" first
$.each(messages, function(key, value) {

    if(value != null) {
        $("#messages").append(value + "<br>");
    }

});

if you then load messages realtime/dynamically with latest first, you can use .prepend()

Upvotes: 6

RobG
RobG

Reputation: 147413

In it's simplest form, you can have:

messages.push(message);
messages.length > 9 && messages.shift();

That will add new messages on the end and remove one from the front once the length gets to 10.

Upvotes: 1

Matthias Tylkowski
Matthias Tylkowski

Reputation: 517

What kind of order do you expect ? You put the entries in the beginning of the array, so the order is inversed.

For example:

addmessage('test'); addmessage('test2'); addmessage('test4');
addmessage('test6'); addmessage('test23'); addmessage('test34');
addmessage('test32'); addmessage('test3'); addmessage('test45');
addmessage('test7'); addmessage('test8');

Results in an array like this:

["test8", "test7", "test45", "test3", "test32", "test34", "test23", "test6", "test4", "test2"]

if you want to have it the other way around you function should look like this:

function addmessage(message){
  messages.push(message);
  messages.shift();
}

Which results in the inverse:

["test2", "test4", "test6", "test23", "test34", "test32", "test3", "test45", "test7", "test8"]

Upvotes: 0

gpasci
gpasci

Reputation: 1440

Try this solution, maybe you want you items in the reverse order?

Upvotes: 0

Related Questions