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

208
Visualizações
Sorting an Array that consists of numbers, BUT can include strings

I am facing an issue where I get results from API(mainly array of numbers), but if the devs make mistake and leave the field empty I will get empty string (""). I am trying to sort this array in an ascending order and move the empty strings in the back of the Array, like that:

let arr = [3, 4, "", 1, 5, 2]   // Example Array from api

This array, when modified should become:

let res = [1, 2, 3, 4, 5, ""]

I tried using the arr.sort() method, but the results look like that:

let res = ["",1 ,2 ,3 ,4 ,5]

For some reason when the element is string, the sort method puts it in the front, not in the end like it does with undefined or null for example.

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

0

Method 1

let arr = [3, 4, "", 1, 5, 2];
const res = arr.sort((a, b) => {
    if (typeof a === 'string') {
        return 1;
    } else if (typeof b === 'string') {
        return -1;
    } else {
        return a - b;
    }
}
);

console.log(res)

Output:

[ 1, 2, 3, 4, 5, '' ]

Method 2

const res = (arr) => {
    let newArr = [];
    let strArr = [];
    for (let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === 'string') {
            strArr.push(arr[i]);
        } else {
            newArr.push(arr[i]);
        }
    }
    return newArr.concat(strArr);
}

console.log(res(arr));
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