1

So let's say I have my first array (arrayOne) with the values of [1,2,3,3,4,2]. I need to compare this array to another array to check for duplicate values (arrayTwo), then display these values.

So, the final output would be: 1, 2, 3, 4.

The catch is I can only use really basic methods, pretty much just booleans, multiple functions, and loops.

How might I go about this? Searching the internet brings up code similar to this:

for (a = 0; a < array1.length; a += 1) {
    for (b = 0; b < array2.length; b += 1) {
        if (array1[a] !== array2[b])
            array2 = array1
        }
    }
}

output = array2   

... so on so forth, but this doesn't seem to work for me (note my code is not exactly like this, but after searching, this seems to be close to what I am looking for).

Any advice?

VLAZ
  • 26,331
  • 9
  • 49
  • 67

2 Answers2

0

In the inner loop check if the current item is equal to an item in the array. If it is, break the inner loop. Check in the outer loop if b === array2.length. In this case equality means that the loop ended without break, which means - not a duplicate. In this case, push the current item to array2.

var array1 = [1, 2, 3, 3, 4, 2];
var array2 = [];
var a,b;

for (a = 0; a < array1.length; a += 1) {
  for (b = 0; b < array2.length; b += 1) {
    if (array1[a] === array2[b]) break;
  }
  
  if(b === array2.length) array2.push(array1[a]);
}

console.log(array2);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

I'm not sure to understand your question, but I think you want to return the initial array without having duplicate values.

let array = [1, 2, 3, 3, 4, 2];

function removeDuplicates(input) {
  let result = [];
  
  for (i = 0; i < input.length; i++) {
    let currentValue = input[i];
    
    if (result.indexOf(currentValue) == -1) {
      result.push(currentValue);
    }
  }
  
  return result;
}

console.log(removeDuplicates(array));

Here you can find more implementations.

Ionut
  • 1,729
  • 4
  • 23
  • 50