简体   繁体   中英

Javascript: How to check if an array item is greater than twice an item in another array

I have two arrays

let arr1 = [1,2,3,4,5]
let arr2 = [6,7,8,9,10]

What I want to do is check if any item in arr2 is greater than or equal to twice any item in arr1. For example, 6 in arr2 is greater than 2*2 in arr1.

My first solution is

for(let i = 0; i < arr2.length; i++) {
  for(let j = 0; j < arr1.length; j++) {
    if (i >= j * 2) {
      return true
    }
  }
}

Expected result: return true if any item in arr2 is greater than or equal to twice any item in arr1.

But I am in search of a linear solution to this problem.

You could take a miminum value of array1 , get the double and check against the minimum of array2 .

 let array1 = [1, 2, 3, 4, 5], array2 = [6, 7, 8, 9, 10], result = Math.min(...array2) > 2 * Math.min(...array1); console.log(result);

You can first find the absolute minimum at first array and then compare it to the second array.

Reducing it to O(arr1.length + arr2.length)

If twice the minimum is greater than any element in arr2 then none is lower.

This code seems wrong:

if (i >= j * 2)
{
      return true
}

should be

if (arr2[i] >= arr1[j] * 2)
{
      return true
}

Since you want boolean value result, you can use some with combination of find .

 let arr1 = [1,2,3,4,5] let arr2 = [6,7,8,9,10] const num = arr2.some(num => arr1.find(x => num >= (x * 2))) console.log(num);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM