Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through associative array in reverse

Tags:

I'm using a javascript associative array (arr) and am using this method to loop through it.

for(var i in arr) {
    var value = arr[i];
    alert(i =") "+ value);
}

The problem is that the order of the items is important to me, and it needs to loop through from last to first, rather than first to last as it currently does.

Is there a way to do this?

like image 691
Urbycoz Avatar asked Feb 10 '11 11:02

Urbycoz


People also ask

Can we use for loop for associative array?

So as we can see in the example above, we can easily loop through indexed array using for loop. But for Associative Arrays we need to use ForEach loop.

What is associative array example with example?

For example, the following statement defines an associative array a with key signature [ int, string ] and stores the integer value 456 in a location named by the tuple [ 123, "hello" ]: a[123, "hello"] = 456; The type of each object contained in the array is also fixed for all elements in a given array.

Is array reverse fast?

Yes, in Google Chrome in 2016, array. reverse is at least twice faster than anything else.

What does associative array do?

Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice.


1 Answers

Four things:

  1. JavaScript has arrays (integer-indexed [see comments below]) and objects (string-indexed). What you would call an associative array in another language is called an object in JS.

  2. You shouldn't use for in to loop through a JS array.

  3. If you're looping through an object, use: hasOwnProperty.

  4. JavaScript doesn't guarantee the order of keys in an object. If you care about order, use an array instead.

If you're using a normal array, do this:

for (var i = arr.length - 1; i >= 0; i--) {
    //do something with arr[i]
}
like image 196
Skilldrick Avatar answered Oct 07 '22 19:10

Skilldrick