Greg Bialowas
Greg Bialowas

Reputation: 169

JS: Loop forces ascending sorting, how to keep defined order?

I have two loops, one big for all tables and inner, smaller with selected tables (to be groupped later on):

        var tables = data.tables;
        ar_1 = [29, 21, 19, 27, 28];

        for (var i = 12; i < tables.length; i++) {
            for( var j = 0; j < ar_1.length; j++) {
                if(ar_1[j] == tables[i][0]) {
                    div.append(
                        '<img src="xxx"><span>' + tables[i][1] + '</span>'
                    );
                }
            }

Both loops work perfeclty well, the problem I have is that I want to keep order as listed inside the inner array and the output always forces ascending sorting, so the result is 19, 21, 27, 28, 29.

What can I do to keep the order of the result as specified inside the array?

Upvotes: 0

Views: 55

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370639

Try looping through ar_1 in the outer loop instead:

for (var j = 0; j < ar_1.length; j++) {
  for (var i = 12; i < tables.length; i++) {
    if (ar_1[j] == tables[i][0]) {
      div.append(
        '<img src="xxx"><span>' + tables[i][1] + '</span>'
      );
    }
  }
}

You also might consider using array methods instead, which are more functional and arguably easier to read. If each item in ar_1 has one matching element in the tables array, then:

ar_1.forEach((findNum) => {
  const foundTable = tables.find(([num]) => num === findNum);
  div.append(
    '<img src="xxx"><span>' + foundTable[1] + '</span>'
  )
});

Upvotes: 1

Related Questions