0

How can I sort an object, which has an array inside. I need to sort by name in javascript. My object is:

(4) [{...},{...},{...},{...}]
 0: {Age: 10, Name: 'John'}
 1: {Age: 25, Name: 'Maria'}
 2: {Age: 23, Name: 'Ana'}
 3: {Age: 27, Name: 'Pedro'}

The output should be an object like this:

(4) [{...},{...},{...},{...}]
     0: {Age: 23, Name: 'Ana'}
     1: {Age: 10, Name: 'John'}
     2: {Age: 25, Name: 'Maria'}
     3: {Age: 27, Name: 'Pedro'}
  • Have you read the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort_)? Also, your example is sorting by a value, not a key name as mentioned in the title. – mykaf Jan 18 '23 at 18:48

1 Answers1

0

Sort based on the result of String.prototype.localeCompare (note that Array.prototype.sort also mutates the original array)

const data = [{Age: 10, Name: 'John'},
{Age: 25, Name: 'Maria'},
{Age: 23, Name: 'Ana'},
{Age: 27, Name: 'Pedro'},]

const newData = data.sort((a, b) => a.Name.localeCompare(b.Name));

console.log(newData);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34