0

I am trying to loop through an array. The array is basically a list from a .txt file on a server, which looks like this:

12345|Test message
55555|55555's message
12345|Test message 2

I do a simple GET request to the server, then get the response in a variable called res. I then do this:

array = res.split("\n");

for(i = 0; i < array.length; i++) {
    array2 = array[i].split("|");
    if(array2[0] == "12345") {
        console.log(array[1]);
    }
}

It will go through each line of the array, split it on | and then check if the first "element" is 12345. If it is, then write the message in the console. However, I want it to write the last message and not every message. In this case, it will write:

Test message
Test message 2

But I want it to write

Test message 2

The "question" is: Can you loop through the array, but only do something after it has found the last message? Thanks.

3 Answers 3

3

Just store the message in a variable and output it after the loop.

array = res.split("\n");

var logMe;
for(i = 0; i < array.length; i++) {
  array2 = array[i].split("|");
  if(array2[0] == "12345") {
    logMe = array[1];
  }
}
if (logMe) {
  console.log(logMe)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh why didn't I think about that... The message in the variable will just get replaced each time it runs then. Thanks for clearing up my head!
Maybe you can answer this question as well. I want to dismiss the message (it shows itself in a nice box with a dismiss button) but I can't figure out if this is the best way... I basically set a local storage variable "dismiss" to false when the message is shown. When pressing dismiss, set dismiss var to true. On next page load, it checks for new messages, and if the new message != the old stored message, then show it. Do you have any better ideas? Obviously store the old message in a local storage variable so it can be grabbed on other pages.
2

Or you can simply go through the array backwards :)

array = res.split("\n");

var i = array.length;
for(i; i > 0; i--) {
    array2 = array[i].split("|");
    if(array2[0] == "12345") {
        console.log(array[1]);
        break;
    }
}

(exactly your code, just backwards + break; if there is no point observing other lines)

1 Comment

That's pretty much what I asked actually. I find Mark's idea a bit better, but definitely does the job.
-1

This should do it:

for(i = 0; i < array.length; i++) {
array2 = array[i].split("|");
if(array2[0] == "12345") {
    console.log(array[1]);
}
if(i == array.lenght - 1){
System.out.println("Message2");
}

2 Comments

I think you misunderstood the question.
sorry i mixed up java and javaskript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.