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

151
Visualizações
Sorting an array of objects by the rate && alphabetical order

I'm trying to sort an array of objects by the rate and alphabetical order.

So I sorted it by rate successfully. BUT THE PROBLEM is when I tried sorting it by alphabetical order, it doesn't work. I have no idea how to sort it again by alphabetical order.

The source code and the result is written at the bottom.

// This is the success result that I want to get **(sorted by rate && sorted by alphabetic order)**

{
abcd ( title)
lorem ipsum (comment)
5 (rate) 
},

{
efg 
lorem ipsum 
5 
},

{
bdg
lorem ipsum
3
},

{
def
lorem ipsum
3
},

{
abc
lorem ipsum
1
}

Source Code

const Reviews = ({ books, initialData }) => {
  const combinedBooks = initialData.concat(books);

  //   sort by rate
  let sorted = combinedBooks.sort((a, b) => {
    return b.score - a.score;
  });

  //   sort by alphabetical order
    let newSorted = sorted.sort(function (a, b) {
      let fa = a.title.toLowerCase(),
        fb = b.title.toLowerCase();

      if (fa < fb) {
        return -1;
      }
      if (fa > fb) {
        return 1;
      }
      return 0;
    });

  return (
    <section style={{ border: "3px solid green" }}>
      <Header title="Book Review Lists" />
      {sorted.map((review) => {
        const { id, title, comment, score } = review;
        return (
          <Review key={id} title={title} comment={comment} score={score} />
        );
      })}
    </section>
  );
};

export default Reviews;  

//Code Result

{
abc
lorem ipsum
1
},

{
abcd
lorem ipsum 
5 
},

{
bdg
lorem ipsum
3
},

{
def
lorem ipsum
3
},

{
efg ( book title) 
lorem ipsum ( book review )
5 (rate) 
},
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You were sorting by rate first, then sorting alphabetically, so you were getting the items in alphabetical order, then by rank if two items have the same alphabetical order.

To sort that alphabetical list by rank, we do this:

 let newerSorted = [...newSorted].sort((a, b) => {
    return b.score - a.score;
  });

So the list is now sorted by rank & items with the same rank are sorted alphabetically.

Working Example:

const Reviews = ({ books, initialData }) => {
  const combinedBooks = initialData.concat(books);

  //   sort by rate
  let sorted = combinedBooks.sort((a, b) => {
    return b.score - a.score;
  });
  

  //   sort by alphabetical order
    let newSorted = sorted.sort(function (a, b) {
      let fa = a.title.toLowerCase(),
        fb = b.title.toLowerCase();

      if (fa < fb) {
        return -1;
      }
      if (fa > fb) {
        return 1;
      }
      return 0;
    });
    
    let newerSorted = [...newSorted].sort((a, b) => {
    return b.score - a.score;
  });

    
    const Review = (props) => {
        return(
        <li key={props.key}>{props.title} - {props.score}</li>
        );
    }

  return (
  <div>
    <section style={{ border: "3px solid green" }}>
      <p>Sorted alphabetically, then by rank</p>
      {newSorted.map((review) => {
        const { id, title, comment, score } = review;
        return (
          <Review key={id} title={title} comment={comment} score={score} />
        );
      })}
    </section>
    
    <section style={{ border: "3px solid green" }}>
      <p>Sorted by rank, then alphabetically</p>
      {newerSorted.map((review) => {
        const { id, title, comment, score } = review;
        return (
          <Review key={id} title={title} comment={comment} score={score} />
        );
      })}
    </section>
    </div>
  );
};


let initialData = [
    {
        id: 27641,
        title: "abc",
        comment: "m ipsum",
        score: 1
    },
    {
        id: 121232,
        title: "zdseru",
        comment: 'lorem ipsum',
        score: 5,
    },
{
        id: 121232,
        title: "adseru",
        comment: 'lorem ipsum',
        score: 5,
    },

    {
        id: 41,
        title: "new title",
        comment: "lorem ipsum",
        score: 3
    },

    {
        id: 27641,
        title: "xef",
        comment: "lorem ipsum",
        score: 3
    },
    {
       id: 33542,
        title: "ifg",
    comment: "lorem ipsum ( book review )",
        score: 2
},];

let books = [{
    id: 33542,
    title: "new title",
    comment: "comment",
    score: 1
}];

ReactDOM.render(<Reviews books={books} initialData={initialData}/>, document.getElementById('sort'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="sort"></div>

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