OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Determine which numbers are in each of two arrays and how many such numbers there are

  • Thread starter Thread starter Diego Silva
  • Start date Start date
D

Diego Silva

Guest
I have an array with numbers that I have to compare with another array (like 1 to X), what is the best way to:

  1. compare the arrays and retrieve the numbers that are equal
  2. determine the number of elements that are equal (without using .length on the array with numbers are equals)

Example:

Code:
Array 1 = [1, 3, 4, 5, 6, 7, 8, 9, 11, 13, 16]

Array 2 = [1, 2, 3, 7, 9, 12, 16, 17]

In this case, the total number of equal elements is 5

And the equal numbers are: [1, 3, 7, 9, 16]

My method is using forEach and comparing each item and using .length on the array with the numbers that are equal. Is there another way or best way to do this?

Another example using more arrays:

Code:
Arr1 = [1, 2, 3, 5, 6, 7, 8, 10, 15]

Arr2 = [

    [1, 3, 5, 7, 8, 9, 10, 11, 12],

    [2, 5, 6, 7, 9, 10],

    [1, 3, 5, 7, 10, 11, 13, 14, 15]

]

Code:
// Output

6, [1, 3, 5, 7, 8, 10]

5, [2, 5, 6, 7, 10]

7, [1, 3, 5, 6, 7, 10, 15]

<p>I have an array with numbers that I have to compare with another array (like 1 to X), what is the best way to:</p>
<ol>
<li>compare the arrays and retrieve the numbers that are equal</li>
<li>determine the number of elements that are equal (without using .length on the array with numbers are equals)</li>
</ol>
<p>Example:</p>
<pre class="lang-none prettyprint-override"><code>Array 1 = [1, 3, 4, 5, 6, 7, 8, 9, 11, 13, 16]

Array 2 = [1, 2, 3, 7, 9, 12, 16, 17]
</code></pre>
<p>In this case, the total number of equal elements is <code>5</code></p>
<p>And the equal numbers are: <code>[1, 3, 7, 9, 16]</code></p>
<p>My method is using <code>forEach</code> and comparing each item and using <code>.length</code> on the array with the numbers that are equal. Is there another way or best way to do this?</p>
<p>Another example using more arrays:</p>
<pre class="lang-javascript prettyprint-override"><code>Arr1 = [1, 2, 3, 5, 6, 7, 8, 10, 15]

Arr2 = [

[1, 3, 5, 7, 8, 9, 10, 11, 12],

[2, 5, 6, 7, 9, 10],

[1, 3, 5, 7, 10, 11, 13, 14, 15]

]
</code></pre>
<pre class="lang-none prettyprint-override"><code>// Output

6, [1, 3, 5, 7, 8, 10]

5, [2, 5, 6, 7, 10]

7, [1, 3, 5, 6, 7, 10, 15]
</code></pre>
 
Top