The order of my array always changes when i do a foreach loop. How can I keep the order of the array.
var array1 = [{id:1, name:'foo'},{id:2, name:'bar'},{id:3, name:'lol'}]
After i do a foreach and output it to a new array, the order sometimes changes
var array2 = [];
angular.forEach(array1, function(post) {
//for brevity i'll just keep it simple
var sample = {id:post.id, name:post.name};
array2.push(sample);
});
//OUTPUT
var array2 = [{id:3, name:'lol'},{id:1, name:'foo'},{id:2, name:'bar'}]
My question is how can i iterate without changing the order.
array1is actually an array, then this should not be happening. Can you show us what the actual JSON response of your service looks like?forEachseems to work fine. Is there a specific reason why you're using angular's over the typical one?