2

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?

5
  • 3
    No, there's no way to give find that information. Commented Apr 29, 2022 at 11:10
  • 2
    You'll have to implement binary search. Depending on your needs, you can consider making arrOfObjects a Map, keyed by obj.property. Then you get constant access. Commented Apr 29, 2022 at 11:11
  • you'll have to write a manual search for that as find is O(n) Commented Apr 29, 2022 at 11:16
  • Regardless, checking if the array is sorted is O(n) so you've always got that time complexity, might just stick with .find unless there's a sorted flag after a sorting method is called. Commented Apr 29, 2022 at 11:16
  • If you want to perform a binary search, an array is a sub-optimal data structure, you should instead be using an object. Commented Apr 29, 2022 at 11:45

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.