Javascript -- Array

Hi All,

let a = [ 120, 60, 40, 30, 24 ]
let b =[ 1, 2, 3, 4, 5 ]

I want the result array to be [120,60],
since these are the only two elements in array ‘a’ which is divisible by all the elements of array ‘b’

Can someone help with the logic please.


I know this might not be the most efficient way, but I think this process could possibly work?

Loop through all elements of array b:

  • For every element, loop through the (remaining) elements of array a
  • If the element is divisible by the number you’re checking in b, keep the number in the array a. If it is not divisible, remove the element.

This would, in the given example, first check what numbers are divisible by b[0] (aka all).
Second loop through would check if the elements are divisible by b[1] (again, all).
Third loop will check if they are divisible by b[2]. 40 % 3 !== 0 and 40 would therefor be removed from the array a.
Fourth loop will check if the remaining elements are divisible by b[3]. 30 would not pass here and be removed from the loop.
Fifth loop will check if the remaining elements are divisible by b[4]. This will remove 24 and leave only 120 and 60 left in array a.

Keep in mind that you should probably not remove the elements from the element you are checking, since this would mean that you in the third iteration would remove 40 from the array, then it would check if a[3] is divisible, but since 40 is removed, a[3] would then be 24 (basically meaning you don’t check if 30 is divisible by 3).

I hope it made some sense?
I could try to write a small code snippet if it helps, but I’d rather give you the logic idea that I think could solve it :slight_smile:

Thanks, but later on I found out that every() method is more appropriate for this scenario


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.