0

I'm returning a Map from java spring controller to the angularjs controller. The Map in the java controller contains the following keys in the order 11,12,14,15,18,22,25,27,34,29 mapped to a value which i'm sending to the js controller. Issue is when i'm iterating and showing the response on the webpage, it is showing result in the sorted manner like 11,12,14,15,18,22,25,27,29,34. How to prevent this and show in the order i have sent from the java controller (i.e.,11,12,14,15,18,22,25,27,34,29) (Please note the difference is in last two values 34,29)

js code:

angular.forEach($scope.myResponse, function (value, key) {
    //here the results i get are in the order 11,12,14,15,18,22,25,27,29,34.
    //how to show the results as it was sent from java spring controller 11,12,14,15,18,22,25,27,34,29
});
georgeawg
  • 46,994
  • 13
  • 63
  • 85
user3684675
  • 365
  • 4
  • 6
  • 26
  • 1
    Can you check and confirm in network tab of developer tools, if you are receiving it in the order you need? – G_S Feb 16 '18 at 17:27
  • 1
    It is highly unlikely that Angular is doing any kind of sorting on your behalf without your tacit permission. What is the type of map you're getting back - `HashMap`? `TreeMap`? – Makoto Feb 16 '18 at 17:27
  • Its a LinkedHashMap@Makoto – user3684675 Feb 16 '18 at 17:46

1 Answers1

0

Chrome sorts propery names if they can be parsed as integers.

From the Docs:

Wrong order in Object properties interation

ECMA-262 does not specify enumeration order. The de facto standard is to match insertion order, which V8 also does, but with one exception:

V8 gives no guarantees on the enumeration order for array indices (i.e., a property name that can be parsed as a 32-bit unsigned integer).

Remembering the insertion order for array indices would incur significant memory overhead.

— Chromium issue #164

To guarantee the order, send the data as an array of key/value pairs.

See also:

georgeawg
  • 46,994
  • 13
  • 63
  • 85