How to Guarantee the Order of Array Returned by JavaScript Object.entries()?

Objects are unordered by design. Depending on your needs, you could do the following:

Sort the Object Entries Array to Have a Specific Order

In cases where you have the need for a certain type of ordering of object entries array (returned by the Object.entries() method), you can simply sort the resulting array. This would guarantee the order you expect.

For example, the following will sort the resulting array from Object.entries() in descending order:

const obj = { 100: 'foo', 3: 'bar', 11: 'baz' };
const sortedPairs = Object.entries(obj).sort((a, b) => b[0] - a[0]);

console.log(sortedPairs); // [['100', 'foo'], ['11', 'baz'], ['3', 'baz']]

You can also refactor the sort compare function using the destructuring syntax like so:

const obj = { 100: 'foo', 3: 'bar', 11: 'baz' };
const sortedPairs = Object.entries(obj).sort(([a], [b]) => b - a);

console.log(sortedPairs); // [['100', 'foo'], ['11', 'baz'], ['3', 'baz']]

Use Map() to Preserve Insertion Order

You can use a Map, instead of an object literal, in which the order is guaranteed. It uses insertion order:

const map = new Map();
map.set(100, 'foo');
map.set(3, 'bar');
map.set(11, 'baz');

const entries = map.entries();

console.log([...entries]); // [['100', 'foo'], ['3', 'baz'], ['11', 'baz']]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.