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

378
Visualizações
get the specific index of element in the array

I have a list of different units:

const unitList = [1, 10, 36, 50, 20]; // all different numbers and all numbers are above 0
const unit = 13; // this is not included in unitList and not more that max number in unitList

And I want to get the index of unit in which unit should be placed before. for instance:

const unit = 13; returns index 4 because it should be placed before 20

const unit = 35; returns index 2 because it should be placed before 36

function getUnitPosition() {

            if(!unitList.length) return 'before add new unit';
            const max = Math.max(...unitList);
            if(unit > max) return 'before add new unit';
            const min = Math.min(...unitList);
            if(unit < min) return columns[0].id;

            for(let a = 0; a < unitList.length; a++) {
                console.log(unit ,  unitList[a], unit < unitList[a])
                if(unit < unitList[a]) return columns[a].id; 
            }
}

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

0

You could take the first found index with a smaller value than unit. For any other smaller value check the value to get the smallest one.

const
    getIndex = (data, unit) => {
        let index;
        for (let i = 0; i < data.length; i++) {
            if (
                unit < data[i] &&
                (index === undefined || data[i] < data[index])
            ) index = i;
        }
        return index;
    },
    unitList = [1, 10, 36, 50, 20];
    // 13                      ^^
    // 35              ^^      
    
console.log(getIndex(unitList, 13)); // 4 placed before 20
console.log(getIndex(unitList, 35)); // 2 placed before 36

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