If I have an array and I want to call map() to that array. Will the result returned from map ever going to have different order from array?
const array = [1,2,3,4,5,6,7,8,9];
const mappedArray = array.map((num) => {
return num * num;
})
console.log(mappedArray);
The mappedArray will ever be [1,4,9,16,25,36,49,64,81] or it is possible that it changes to something else (not the same order)?
What if I make an API call inside the map like the following
const mappedArray = array.map(async (num) => {
return await api(num);
})
// remote API
function api(num) {
return dynamoDbClient.getItem(num);
}
CodePudding user response:
No, map
will always iterate through the array in order. Unless the array is changed elsewhere in your code, the order of the resulting array will not change. The output will always be the same if the input is the same.
Run this code 1000 times and the array will be the same every time.
const array = [1,2,3,4,5,6,7,8,9];
const mappedArray = array.map((num) => {
return num * num;
})
console.log(mappedArray);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>