Skip to content Skip to sidebar Skip to footer

How To Find Index Of Element In Javascript If It Present?

Could you please tell me how to find the index. I have a problem Given a sorted array and a target value, return the index if the target is found. If not, return the index where it

Solution 1:

Problem is with your last statement

return nums.length %2 == 0 ? mid +1 : mid

So in the last case your mid = 1 as since the length of array is two you're adding mid + 1

One approach is to return the value from while itself in case your target isn't found in array, on condition when start === end

const searchInsert = function(nums, target) {
  if (target > nums[nums.length - 1]) return nums.length;
  if (target <= nums[0] || nums.length === 0) return0;
  let start = 0,
    end = nums.length - 1,
    mid = Math.floor((start + end) / 2);
  while (start < end) {
    if (nums[mid] == target) return mid
    if (nums[mid] > target) end = mid - 1;
    if (nums[mid] < target) start = mid + 1;
    if(start >= end){
      return nums[mid] > target ? mid  : mid + 1 
    }
    mid = Math.floor((start + end) / 2);
  }
};

console.log(searchInsert( [1,3,5,6], 5)) // 2console.log(searchInsert([1,3,5,6], 2)) // 1console.log(searchInsert([1,3,5,6], 7)) // 4console.log(searchInsert([1,3], 2)) // 1console.log(searchInsert([1,2,3,5], 4)) // 3console.log(searchInsert([1,2,3,4,5,7,9,10,15], 8)) //6console.log(searchInsert([0, 1, 3, 4], 2)) // 2console.log(searchInsert([1],1)) // 0console.log(searchInsert([0],1)) // 1console.log(searchInsert([],1)) // 0

Solution 2:

What you can try is using the <Array>.indexOf(n) and <Array>.sort() like so:

let arr = [1,3,5,6]
const needle = 0functionsearchInsert (arr, needle) {
  let index = arr.indexOf(needle)

  if (index === -1) {
    arr.push(needle)
    arr = arr.sort((x, y) => x - y)
    index = arr.indexOf(needle)
  }

  return index
}

Post a Comment for "How To Find Index Of Element In Javascript If It Present?"