0

In my Express route I grab a bunch of entries from a MySQL database. These entries are words, and have associated line numbers, so that all words on the same line need to be printed together before a line break.

word  |  section
----------------
Lorem |     1    
ipsum |     1
dolor |     1
sit   |     2
amet  |     2

Using doT.js as my templating engine, I need to print this out as

Lorem ipsum dolor
sit amet

I loop through the array of MySQL results and print out the word. But I can't figure how to compare the line number of the current index to that of the previous index. My first inclination is to store a variable for the current line, and compare it to the previous line. If they are different, then I can print a <br>. But I am having trouble figuring out how to do it.

Will I have to use a helper method (and if so, can someone link a good tutorial)? Or are there easier ways to accomplish this?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Kramhsiri
  • 119
  • 9

1 Answers1

0

Assusming you have this array:

var arr = [ { "word":"lorem", "section": "1"}, { "word":"ipsum", "section": "1"}, { "word":"dolor", "section": "1"}, { "word":"sit", "section": "2"}, { "word":"amet", "section": "2"} ]

You can try it in this function:

function printWordsOnLines(arr) {
    var currentLine = 1;
    var output = "";
    arr.forEach(function(line) {
        if(currentLine<line.section) {
            currentLine=parseInt(line.section);
            output+="<br>";
        }
    output+=line.word + " ";
    })
    return output;
}

which is going to have this output:

"lorem ipsum dolor <br>sit amet "

You can further adjust this to your exact needs.

Evgeni Atanasov
  • 482
  • 1
  • 5
  • 13