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

188
Visualizações
Please do I interprete this ternary operator?

Please if this function was to be converted to a "normal" if else statement, how would it look like?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I want to add another condition, but I'm finding it hard to read or digest the current flow.

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

0

First lets expand the code to make it (slightly) easier to read.

Note that the ?: contains questionable logic, use of === seems to suggest it is trying to handle sorting an array of mixed types, but then using non-strict < and > comparisons. So for the purposes of the rest of this answer I am going to assume it is not trying to sort mixed typed arrays or that if it is, it will ignore strict type comparisons (ie the === should really be ==)

function orderArr (arr: any[], key: string) {
  function sorter(a, b) {
    return (
      (a[key] > b[key]) 
      ? 1 
      : (a[key] === b[key]) 
        ? (
          (a[key] > b[key]) 
            ? 1 
            : -1
        ) 
        : -1
    );
  }
  return arr.sort(sorter);
}

export orderArr;

Now lets re-write the overcomplicated ?: expression (overcomplicated not because of the ?: syntax but because its doing more than it needs to) and rewrite as if then elses (note, this code is still wrong)

function sorter(a, b) {
   if (a[key] > b[key]) {
     return 1;         // return 1 if a > b 
   } else {
     if (a[key] === b[key]) {        // questionable logic
       if (a[key] > b[key]) {        // questionable logic
         return 1;
       } else {
         return -1;      // will always return -1 (wrong, a == b should return 0)
       }
     } else {
       return -1;     // return -1 if a < b
         // or if type of a does not equal type of b (questionable)
     }
   }
}

Now lets simplify and fix the bug (ie remove the strict type comparison). Using a technique called early return (also called guard clauses), and avoiding using else as it adds unnecessary indentation and complication

function sorter(a, b) {
   if (a[key] > b[key]) return 1;
   if (a[key] < b[key]) return -1;
   return 0;
}

Or if you prefer, using ?: syntax

function sorter(a, b) {
   return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
}

If you are sorting numbers, you can use a little trick to further simplify the code. Sort expects a 0 if a and b are equal, a negative value if a < b and a positive value if a > b, so for numeric sorting we can simply do

function sorter(a, b) {
   return a[key] - b[key];
}

Now, lets put all the simplified code back together into a single line. First for any type of array.

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);

and for a numerical only array

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] - b[key]);
about 4 years ago · Juan Pablo Isaza Relatório

0

Edit:

According to @Erich Kitzmueller's answer, I removed a[key] === b[key] part:

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => 
{
    if(a[key] > b[key]){
        return 1;
    } else {
        return -1;
    }
}
);

Original Answer:

I am not sure about sort function's structure but the if statement might look like below:

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => 
{
    if(a[key] > b[key] || a[key] === b[key]){
        return 1;
    } else {
        return -1;
    }
}
);
about 4 years ago · Juan Pablo Isaza Relatório

0

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

is equal to:

export const orderArr = (arr: any[], key: string) => {
    return arr.sort((a, b) => {
        if (a[key] > b[key]) {
            return 1;
        } else if (a[key] === b[key]) {
            if (a[key] > b[key]) {
                return 1;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    })
}

I'm strongly believe it's not necessary to use 3+ level nested ternary operators anywhere 'cause it's huge code readability sacrifice for no reason.

Feel free to rewrite method to common if/else or switch statements to keep your code clear.

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