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()

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay