How to sort an object by its properties in JavaScript

In this Article we will go through how to sort an object by its properties only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const sort = obj => Object.keys(obj).sort().reduce((p, c) => (p[c] = obj[c], p), {});

#Example

const colors = {
    white: '#ffffff',
    black: '#000000',
    red: '#ff0000',
    green: '#008000',
    blue: '#0000ff',
};
sort(colors);
/*
{
    black: '#000000',
    blue: '#0000ff',
    green: '#008000',
    red: '#ff0000',
    white: '#ffffff',
}
*/