Nicolas Hochard
Nicolas Hochard

Reputation: 45

How to find a common multple by creating and looping through 2 arrays at the same time, javascript

I am looking for a way to create an 2 arrays of integers at the same time until one common value is find in the 2 arrays. I don't know when this common integer will be find, so I don't know where to stop my loop until the match is find.

Here is the example that I want to achieve when the 2 array are already created:

var arr1 = [3, 6, 9, 12, 15, 18, 21, 24, 27];
var arr2 = [5, 10, 15, 20, 25, 30, 35, 40, 45];
var arr3 = [];

for (var i = 0; i < arr2.length; i++){

if (arr1.includes(arr2[i])){
  arr3.push(arr2[i]);
}
}

here, the common integer is 15. arr3 return 15.

I am trying to get to the same result without knowing with the common multiplier will be find but can't find the correct way to do it.

I would like to achieve this by doing something like this :

var num1 = [3, 5];

var res = [];

for (var i = 1; i <= 10; i++){
  if (num1[0]*i.includes(num1[1]*i)){
    res.push(i);
  }
}

Any idea how I could achieve this?

Thank you!

Upvotes: 1

Views: 65

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50787

If you're looking for this as a way to find the least common multiple (LCM), then this is far overblown, but if you want the list of multiples of each up to the least common multiple, this might do it:

const last = (arr) => arr[arr.length - 1]

const buildMultiples = (a, b) => {
  while (last(a) < last(b)) {
    a.push(last(a) + a[0])
  }
  if (last(a) == last(b)) {
    return [a, b]
  }
  return buildMultiples (b, a)
}

console.log(buildMultiples ([3], [5]))

But if you're just looking for the LCM, then you should try a purely numeric technique.

Note that I use recursive rather than iterative techniques here. While there are many cases for which either makes sense, here it seems to me that any iterative technique would be much less understandable than this recursive one. (I'd love to be proven wrong on this.)

(Also note that there is no error checking. If you don't supply two arrays holding single positive integers, things could go very wrong.)

Upvotes: 1

Related Questions