home ~ socials ~ other projects

Sort a JavaScript Object/Hash by Value

JavaScript

const data = {
  bravo: "This is Bravo",
  charlie: "This is Charlie",
  alfa: "This is Alfa",
  delta: "This is Delta",
}

const sorted = Object.entries(data)
  .toSorted((a,b) => a[1].localeCompare(b[1]));

sorted.forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});
Output:
alfa: This is Alfa
bravo: This is Bravo
charlie: This is Charlie
delta: This is Delta
-- end of line --

References