Loop through Object in Reverse Order using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Photo from Unsplash

Loop through Object in Reverse Order #

To loop through an object in reverse order:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Call the reverse() method to reverse the array.
  3. Use the forEach() method to iterate over the array 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's properties manually.

We used the Array.reverse method to reverse the keys array.

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.