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

116
Visualizações
What am I doing wrong while trying to sort this array?

Need to sort an array of objects based on a particular value in that object.

const obj = [
    {
        field: "FULL_NAME",
        required: "Y"
    },
    {
        name: "EMAIL",
        required: "N"
    },
    {
        name: "ADDRESS",
        required: "N"
    },
    {
        name: "NUMBER",
        required: "Y"
    },
]


I want to sort this array in a way that fields with required 'Y' come first.

Tried to write a comparison function like this :

const obj = [
    {
        field: "FULL_NAME",
        required: "Y"
    },
    {
        name: "EMAIL",
        required: "N"
    },
    {
        name: "ADDRESS",
        required: "N"
    },
    {
        name: "NUMBER",
        required: "Y"
    },
];

const compare = (a, b) => {
    if(a.required === "Y" && b.required === "N"){
        return 1
    }

    if(a.required === "N" && b.required === "Y"){
        return -1
    }

    return 0;
}

console.log(obj.sort(compare));

How do I fix it so it works?

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

0

You have the 1 and -1 backwards. -1 means the first element argument is sorted first, and 1 means the second element argument is sorted first. See the compareFunction/ sort order table at the Array.prototype.sort() article:

compareFunction(a, b) return value sort order
> 0 sort b before a
< 0 sort a before b
=== 0 keep original order of a and b

const obj = [
    {
        field: "FULL_NAME",
        required: "Y"
    },
    {
        name: "EMAIL",
        required: "N"
    },
    {
        name: "ADDRESS",
        required: "N"
    },
    {
        name: "NUMBER",
        required: "Y"
    },
];

const compare = (a, b) => {
    if(a.required === "Y" && b.required !== "Y"){
        return -1
    }

    if(a.required !== "Y" && b.required === "Y"){
        return 1
    }

    return 0;
}

console.log(obj.sort(compare));

about 4 years ago · Juan Pablo Isaza Relatório

0

Shortest version using ES6

obj.sort((a,b) => a.required > b.required ? -1: 1);

Reference: Sort objects in an array alphabetically on one property of the array

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