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

205
Visualizações
Sorting an array of objects based on all of its property values
function sortedPeopleArray(peopleArray) {
    arrayCopy = [...peopleArray];

    function compare(a, b) {
        const nameA = a.name.toUpperCase();
        const nameB = b.name.toUpperCase();

        let comp = 0;
        if (nameA > nameB) {
            comp = 1;
        } else if (nameA < nameB) {
            comp = -1;
        }
        return comp;
    }

    arrayCopy.sort(compare);

    arrayCopy.sort(function(a,b) {
        return (a.satisfaction - b.satisfaction) * -1;
    });

    arrayCopy.sort(function(a,b) {
        return (a.rating - b.rating) * -1;
    });

    arrayCopy.sort(function(a,b) {
        return (a.age - b.age) * -1;
    });
    
    return arrayCopy;
}

I have attempted to sort an array based on all of its property values but my function does not return the desired output. Is there a better way to approach this?

How would I sort an array of objects (code below) in descending order of:

  1. age (highest to lowest)
  2. rating (highest to lowest)
  3. satisfaction (highest to lowest)
  4. name (by alphabetical order)

These properties are considered exactly in that order when sorting

If two values are equal, then the next property on the list is looked at to determine which person is placed first. eg. if two people have the same rating then the person with a higher satisfaction number is placed first

const array = [
 {
   name: A
   age: 22
   rating: 5
   satisfaction: 2
 },
 {
   name: B
   age: 25
   rating: 7
   satisfaction: 4
 },
 {
   name: C
   age: 22
   rating: 9
   satisfaction: 8
 },
];

The outputted array should be


result = [
{  name: B,
   age: 25,
   rating: 7,
   satisfaction: 4,
}, 
{  name: C
   age: 22
   rating: 9
   satisfaction: 8
}, 
{  name: A
   age: 22
   rating: 5
   satisfaction: 2
 },
];
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to apply the comparisons one after another, linked by the "or" (||) operator. The or operator will not process its second argument if the first one was found to be truthy, i. e. if it returned a value different from 0.

Comparing numbers is easiest accomplished by a simple subtraction. Strings can be compared with String.prototype.localeCompare():

const arr = [{name: "A",age: 22,rating: 5,satisfaction: 2},{name: "B",age: 25,rating: 7,satisfaction: 4},{name: "C",age: 22,rating: 9,satisfaction: 8}];

arr.sort((a,b)=>
 b.age-a.age ||
 b.rating-a.rating ||
 b.satisfaction-a.satisfaction ||
 b.name.localeCompare(a.name))

console.log(arr);

about 4 years ago · Juan Pablo Isaza Relatório

0

Do the comparison all in one function.

function compare(oA, oB)
{
  if(oA.age == oB.age)
  {
    if(oA.rating == oB.rating)
    {
      if(oA.satisfaction == oB.satisfaction)
      {
        const nameA = oA.name.toUpperCase();
        const nameB = oB.name.toUpperCase();

        let comp = 0;
        if (nameA > nameB) {
            comp = 1;
        } else if (nameA < nameB) {
            comp = -1;
        }
        return comp;
      }
      else
      {
        return oB.satisfaction - oA.satisfaction;
      }
    }
    else
    {
      return oB.rating - oA.rating;
    }
  }
  else
  {
    return oB.age - oA.age;
  }
}

const array = [
 {
   name: 'A',
   age: 22,
   rating: 5,
   satisfaction: 2
 },
 {
   name: 'B',
   age: 25,
   rating: 7,
   satisfaction: 4
 },
 {
   name: 'C',
   age: 22,
   rating: 9,
   satisfaction: 8
 },
];

let arrayCopy = [...array];
arrayCopy.sort(compare);
console.log(arrayCopy)

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