JavaScript - Parse array items in reverse order

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts: 48

JavaScript - Parse array items in reverse order

How can I parse the array items in reverse order, in JavaScript?
I have a Div and an array with numbers in JS code, like this:

Code: Select all

<div id="dv1"></div>
<script>
var ary = [13, 2, 8, 56, 9];
// here get each ary item in reverse order: 9, 56, 8, 2, 13
</script>
In #dv1 I want to add: 9, 56, 8, 2, 13
Thanks.

MarPlo Posts: 186
The simplest way is to use a reverse for() loop (with "i--").
See this example:
<div id="dv1"></div>

Code: Select all

<script>
var ary = [13, 2, 8, 56, 9];
var itms = '';
for(var i=ary.length; i--;) {
  itms += ary[i] +', ';
}
document.getElementById('dv1').innerHTML = itms.replace(/(, )$/, '');  // replace() to removes last ','
</script>
- Note, in this reverse for() loop you must have ";" after "i--".

Another way, is to apply the reverse() JavaScript function to that array, then use a simple for() instruction to parse the array items.
Example:

Code: Select all

<div id="dv1"></div>
<script>
var ary = [13, 2, 8, 56, 9];
ary.reverse();
var itms = '';
for(var i=0; i<ary.length; i++) {
  itms += ary[i] +', ';
}
document.getElementById('dv1').innerHTML = itms.replace(/(, )$/, '');  // replace() to removes last ','
</script>
- Or, with forEach() function:

Code: Select all

var ary = [13, 2, 8, 56, 9];
ary.reverse();
var itms = '';
ary.forEach(function(itm) {
  itms += itm +', ';
});

alert(itms);  // 9, 56, 8, 2, 13,
- forEach has the benefit that you don't have to declare indexing and entry variables in the containing scope, and so nicely scoped to just that iteration.

Similar Topics