-2

I need to create a function that checks all numbers in an array and print them out. My idea was something similar to this:

  var array = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99]; 
  var string = "";
  var len = array.length;

After declaring the variables, i start to loop them:

  for (var i = 0; i < len; i ++) {
     for (var j = 0; j < len; j ++) {
        //console.log(array[i], array[j]);
     }
  }

Console prints me value in this order:

3 3
3 6
3 67
. .
6 3
6 6
6 67
. .

I thought to create a if statement checking if array[i] is equal to array[j] then pushing the content in a new string.

Yevgeniy
  • 17
  • 6
  • 2
    I'm confused as to what you want to do. Check the numbers how? – fstanis May 26 '19 at 17:54
  • 3
    And how is 3, 6 and 67 printed when the array doesn't have any of those? Do you want to get the numbers which appear more than once? – adiga May 26 '19 at 17:54
  • Yeah as mentioned in the title, i want to check multiple numbers in an array by using == //console.log(array[i], array[j]); – Yevgeniy May 26 '19 at 18:02
  • [Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array](https://stackoverflow.com/questions/840781) – adiga May 26 '19 at 18:09

2 Answers2

1

You need to iterate in the outer loop until the element before the last item and in the inner loop start from the actual index plus one, to prevent to check the same element.

If duplicate is found, push the value to the duplicates array.

var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
    len = array.length,
    i, j,
    duplicates = [];

for (i = 0; i < len - 1; i++) {
  for (j = i + 1; j < len; j++) {
    if (array[i] === array[j]) duplicates.push(array[i]);
  }
}

console.log(duplicates);

A shorter approach by using a Set

var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
    found = new Set,
    duplicates = array.filter(v => found.has(v) || !found.add(v));

console.log(duplicates);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can also use Set with Array.filter and Array.indexOf:

let data = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99]

let r = new Set(data.filter((v, i, a) => a.indexOf(v) !== i))

console.log(Array.from(r))

The idea is to filter the items to those who have multiple indexes found and then add them to the Set. Since Set stores unique items only it will take care of the duplicates and you get the final result.

We take advantage of the fact that Array.filter provides 3 arguments to the iteratee function - value (v), current index (i) and the actual array (a).

Akrion
  • 18,117
  • 1
  • 34
  • 54