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

104
Visualizações
Tell JavaScript my array is sorted when searching for an element

I have an array of objects that I know is sorted by one of the object properties. I want to look in the array for the object with that property equalling a specific value, so I do this:

arrOfObjects.find((obj) => obj.property === value)

However, this is an O(n) operation for an unsorted array, but O(log n) using binary search on sorted arrays.

Is there any way to tell JavaScript my array is sorted when doing a .find(), or do I have to manually implement a binary search?

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

0

There is no built-in binary search functionality in JavaScript.

Even if there was Array#find() itself cannot benefit from it, since it expects a callback that returns true or false. There is no way to determine if the expected result is before or after a given point based on a boolean result which only indicates a match.

about 4 years ago · Juan Pablo Isaza Relatório

0

You could implement a protoype of Array, like

Array.prototype.binaryFind = function (callbackFn, thisArg) {
    // code
};

Then you need to specify a function as callback which has three states to determin the find, left or right side. An idea is to take the same approach like for sorting where an value takes the order, depending of negative, zero or positive which shows the relation of the values.

function findInObjects(key, value) {
    return function (object, index, array) { // 
        if (object[key] === value) return 0;
        if (object[key] < value) return -1;
        else return 1;
    }
}
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