Loop through Object in Reverse Order using JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

Loop through Object in Reverse Order #

To loop through an object in reverse order, use the Object.keys() method to get an array of the object's keys and call the reverse() method to reverse the array. You can then iterate over the array using the forEach() method and access the object's keys and values in reverse order.

index.js
const obj = { a: 'one', b: 'two', c: 'three', }; // ๐Ÿ‘‡๏ธ ['c', 'b', 'a'] const reversedKeys = Object.keys(obj).reverse(); reversedKeys.forEach(key => { console.log(key, obj[key]); // ๐Ÿ‘‰๏ธ c three, b two, a one });

The first step is to get an array of the object's keys by using the Object.keys method.

index.js
const obj = { a: 'one', b: 'two', c: 'three', }; const keys = Object.keys(obj); console.log(keys); // ๐Ÿ‘‰๏ธ ['a', 'b','c']
The Object.keys() method returns the keys ordered in the same way as given by looping over the object properties manually.

To reverse the keys array, we use the Array.reverse method.

The reverse() method reverses the elements in the array in place and returns the result.

index.js
const obj = { a: 'one', b: 'two', c: 'three', }; const keys = Object.keys(obj); console.log(keys); // ๐Ÿ‘‰๏ธ ['a', 'b','c'] const reversed = keys.reverse(); console.log(reversed); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a']
It's irrelevant in this scenario, but note that the reverse() method changes the contents of the original array.
index.js
const arr = ['a', 'b', 'c']; const reversed = arr.reverse(); console.log(reversed); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a'] console.log(arr); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a']

To circumvent mutating the original array, you will often have to create a copy before calling the reverse() method.

index.js
const arr = ['a', 'b', 'c']; const reversed = [...arr].reverse(); console.log(reversed); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a'] console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

The last step is to use the Array.forEach method to iterate over the reversed array of keys.

We can then use each key to access the values in the object.

Here's the complete example:

index.js
const obj = { a: 'one', b: 'two', c: 'three', }; const reversedKeys = Object.keys(obj).reverse(); reversedKeys.forEach(key => { console.log(key, obj[key]); // ๐Ÿ‘‰๏ธ c three, b two, a one });

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee