DEV Community

Davy Chen
Davy Chen

Posted on

Rarely Heard Knowledge Of JavaScript

Rarely Heard Knowledge Of JavaScript

Sometimes you'll want an automatically ordered Dictionary. The key-value pairs of the Dictionary get ordered by the keys after insertion.

In JS, the data structure of Map() won't do that for you. While, an Object can.

An Object is this:

{}

But only when the keys are numbers and the numbers >= 0 (Non-fractional), the keys to be ordered ascendingly.

Otherwise, If the numbers are fractional, they are going to be taken as strings, and strings are to be arranged by insertion order in an Object.

Image description

JS code that gives output in the picture:

const list = {};
const length = 15;

for (let i = 0; i < length; i++) {
 let value = Math.random() * 1000000;
 list[value] = i + 1;
}

const keys = Object.keys(list);
const values = Object.values(list);

for (let i = 0; i < keys.length; i++) {
 console.log(keys[i], values[i]);
}
Enter fullscreen mode Exit fullscreen mode

And if you need to tell that if the keys are fractional or integral, you can use this:

Number.isInteger()

Top comments (0)