re: Linear and Binary Search in JavaScript VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION
 

Do you mean how would you pass in an array of objects? I modified the function a bit here to allow you to input a sorted array of objects, the key you are targeting, and the value you are searching for. (This assumes that the array is already sorted by the specific key you're looking at).

function binarySearch(sortedArrayofObjects, keyToTarget, valueToFind) {
  var lowIndex = 0;
  var highIndex = sortedArrayofObjects.length - 1;
  while (lowIndex <= highIndex) {
    var midIndex = Math.floor((lowIndex + highIndex) / 2);
    if (sortedArrayofObjects[midIndex][keyToTarget] == valueToFind) {
      return midIndex;
    } else if (sortedArrayofObjects[midIndex][keyToTarget] < valueToFind) {
      lowIndex = midIndex + 1;
    } else {
      highIndex = midIndex - 1;
    }
  } return null;
}

var sortedORainbowObj = [
  {
    id: 5,
    color: "blue"
  },
  {
    id: 4,
    color: "green"
  },
  {
    id: 6,
    color: "indigo"
  },
  {
    id: 2,
    color: "orange"
  },
  {
    id: 1,
    color: "red"
  },
  {
    id: 7,
    color: "violet"
  },
  {
    id: 3,
    color: "yellow"
  }
];

console.log(binarySearch(sortedORainbowObj, "color", "yellow")); // returns 6
console.log(binarySearch(sortedORainbowObj, "color", "maroon")); // returns null

 

Nice function, I'm looking forward to your next post.

 

The clean way to extend function to generic types is to override a compare function I'd say

I fully agree, nonetheless that would require using typescript, I had thought about making use of the valueOf function, however I like the way @stepho did it since it is easier to reuse, even more for js newcomers.

code of conduct - report abuse