Alphabetizing an object array

Asked

Viewed 1,055 times

0

I have an array of objects and want to put in alphabetical order but I’m not getting by javascript, I’ll put as the array is structured and the code to call on the page

var json = [
  {
        "ID":"1",
        "TÍTULO":"Algum titulo",
        "AUTORES":[
              {
                    "AUTOR":"Fulano",
                    "INSTITUIÇÃO":""
              },
              {
                    "AUTOR":"Cicrano",
                    "INSTITUIÇÃO":"instituição"
              },
              {
                    "AUTOR":"Nomes",
                    "INSTITUIÇÃO":"Nomes"
              }
        ]
  },
  {
        "ID":"2",
        "TÍTULO":"Algum titulo 2",
        "AUTORES":[
              {
                    "AUTOR":"algum nome",
                    "INSTITUIÇÃO":"Nomes"
              },
              {
                    "AUTOR":"Nomes",
                    "INSTITUIÇÃO":"Nomes"
              }
        ]
  }
];

var filter = json.filter(x => x.AUTORES.some(autor => autor.AUTOR));    
    for(var i=0;i<filter.length; i++){
        for(var j=0;j<filter[i].AUTORES.length; j++){
            var html = '<tr bgcolor="#F5F5F5">';
            html +='<td width="13%">' +filter[i].AUTORES[j].AUTOR+'</td>';
            html +='</tr>';
            $('table tbody').append(html);
        }
    }
  • 1

    It is quite vague your question, sort in alphabetical order by which property?

  • On the property Authors

1 answer

0

The callback passed in Sort takes two arguments, which are the two items you should compare, and then returns a number greater than 0 to say that the first element is greater, or vice versa.

In your case, to order by title would be:

var ordenados = json.sort((livroA, livroB) => livroA['TÍTULO'] > livroB['TÍTULO'] ? 1 : -1);

To organize by author you would have to organize the name of the authors too, it is not an efficient code, but it works:

var ordenados = json.sort((livroA, livroB) => 
    livroA.AUTORES.map(a => a.AUTOR).sort().join(' ') > 
    livroB.AUTORES.map(a => a.AUTOR).sort().join(' ') ? 1 : -1);

And if it’s necessary to skip the high box:

var ordenados = json.sort((livroA, livroB) => 
    livroA.AUTORES.map(a => a.AUTOR.toLowerCase()).sort().join(' ') > 
    livroB.AUTORES.map(a => a.AUTOR.toLowerCase()).sort().join(' ') ? 1 : -1);
  • The connection between the filter and the sort You’re a little confused in your answer

  • I think I misread the code posted.

  • The title I managed to do, but the authors did not, I tried with this method from above but it is not in alphabetical order

Browser other questions tagged

You are not signed in. Login or sign up in order to post.