How find the array index for two array comparision and return once array item less than another?

A simple for loop will suffice. In our loop, we already have the index so we just compare the first array at this index with the second array at this index.

const compareArray = (arr1, arr2) => {  
  let startIndex = 0
  if (arr1[0] < arr2[0]) {
    // find the index from arr1 that is greater than arr2
    startIndex = arr1.findIndex((a, index) => a > arr2[index])

  for (let i = startIndex; i < arr1.length; i++) {
    if (arr1[i] < arr2[i]) {
      return i

const exampleArr1 = [15,9,7,5,3,1]
const exampleArr2 = [2,6,8,12,17,22]
const exampleArr3 = [1,2,4,5,15,9,7,5,3]
const exampleArr4 = [2,3,5,6,2,6,8,12,17]

console.log(compareArray(exampleArr1, exampleArr2))
console.log(compareArray(exampleArr3, exampleArr4))

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top