I have an unsorted array:
const x = [10, 5, 1, 8, 3, 6, 5, 4, 7, 2, 5, 9, 0];
I want to convert this array into a hash-table in which the keys are the elements of the array, and the values are the number of times the element in this array occurs. So I do next:
const map = {};
x.forEach(item => {
if (!map.hasOwnProperty(item)) {
map[item] = 0;
}
map[item] += 1;
})
The thing I do not understand is why my unsorted array is getting sorted in resulting hash-table?
{
'0': 1,
'1': 1,
'2': 1,
'3': 1,
'4': 1,
'5': 3,
'6': 1,
'7': 1,
'8': 1,
'9': 1,
'10': 1
}
The data structre used in your code is Object, when Objects.keys is used or iteration is used, it will always retrun in ascending order. If you want to maintain the insertion order. Try map or set, for detail please refer below.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set