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.
Iterating over an Array is guaranteed to be in order. This is not true of dictionaries. If you want to create a new array, you can simply do something like this:
var array2 = array1.map(function(post) {
return {id: post.id, name: post.name};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With