Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
Sort object by category and name

Is there a way in jQuery or javascript to sort the data by category in descending order and name in ascending order?

I have tried to sort the data twice similar to the sample code below, but it's not working as it should be.

The data should be listed by category like B, A and will sort next by name like AA, AB, BB and so on.

Sample data and sort script:

var data = {
  0: {
    category: 'A',
    name: 'AA'
  },
  1: {
    category: 'B',
    name: 'BB'
  },
  2: {
    category: 'A',
    name: 'AB'
  },
  3: {
    category: 'A',
    name: 'BB'
  }
}

var items = $( $.map( data, function ( val, i ) {
  return val;
} ) );

// Sort data by category in DESC order.
function sortByCategoryDescOrder( a, b ) {
  if ( a.category < b.category ) {
    return -1;
  }
  if ( a.category > b.category ) {
    return 1;
  }
  return 0;
}

function sortByNameAscOrder( a, b ) {
  if ( a.name < b.name ) {
    return -1;
  }
  if ( a.name > b.name ) {
    return 1;
  }
  return 0;
}

items.sort(sortByCategoryDescOrder);
items.sort(sortByNameAscOrder);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>

The expected output should be:

var data = {
  0: {
    category: 'B',
    name: 'BB'
  },
  1: {
    category: 'A',
    name: 'AA'
  },
  2: {
    category: 'A',
    name: 'AB'
  },
  3: {
    category: 'A',
    name: 'BB'
  }
}

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is my solution:

let data = {
  0: {
    category: 'A',
    name: 'AA'
  },
  1: {
    category: 'B',
    name: 'BB'
  },
  2: {
    category: 'A',
    name: 'AB'
  },
  3: {
    category: 'A',
    name: 'BB'
  }
}

let result=Object.values(data).sort((a,b)=>{
    if (a.category>b.category){
     return -1;
  } else {
    if (a.category<b.category){
         return 1;
    } else {
       if (a.name > b.name) {
         return 1
       } else {
          if (a.name < b.name) {
            return -1
          }
       }
    
    }
  }
});
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Two issues.

  • Your sortByCategoryDescOrder sort return values are incorrect. Descending order sort should return +1 when a < b, -1 when a > b and 0 on a === b.
  • sortByNameAscOrder function, shouldnot compare objects with different category. You have already sorted the array based on category, if you again sort the array by comparing different category value, it will give you the soeted format of original array. You should return 0 for different category values, which means you are not changing order in that case.

Working Fiddle

var data = {
    0: {
        category: 'A',
        name: 'AA'
    },
    1: {
        category: 'B',
        name: 'BB'
    },
    2: {
        category: 'A',
        name: 'AB'
    },
    3: {
        category: 'A',
        name: 'BB'
    }
}

var items = $($.map(data, function (val, i) {
    return val;
}));

// Sort data by category in DESC order.
function sortByCategoryDescOrder(a, b) {
    if (a.category < b.category) {
        return 1;
    }
    if (a.category > b.category) {
        return -1;
    }
    return 0;
}

function sortByNameAscOrder(a, b) {
    if(a.category !== b.category) {
        return 0;
    }
    if (a.name < b.name) {
        return -1;
    }
    if (a.name > b.name) {
        return 1;
    }
    return 0;
}

console.log(items.sort(sortByCategoryDescOrder));
console.log(items.sort(sortByNameAscOrder));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda