0

I have the following

var a = [4,6,12];
var b = [4,6];

for (var i = 0; i < a.length; i++) {
    for (var j = 0; j < b.length; j++) {
       if (a[i] !== b[j]) {
         a.pop();
       }
    }
}

I want to compare the two and remove 12 from a if it is not found in b. I do not want to create a new array with the result just remove from a.

However, if I console log a I get a as empty.

user2025749
  • 201
  • 1
  • 2
  • 11

7 Answers7

1

The reason why a is coming out as empty is because of your double loop. You're comparing each element of a to every other element of b. When you hit a[0] == b[1], obviously, 4 != 6 so you pop it.

Evan Knowles
  • 7,290
  • 2
  • 34
  • 69
1

Try:

var a = [4,6,12];
var b = [4,6];

a.forEach(function(v,i){
    if (b.indexOf(v) === -1) {
        a.splice(i,v);
    }
});

console.log(a); // result [4,6]

JSFiddle

Iteration checks every element of a array and compares to b elements, if certain element doesn't exist in b then that element is removed from a array

nanobash
  • 5,293
  • 7
  • 34
  • 56
0
var a = [4,6,12];
var b = [4,6];

for (var i = 0; i < a.length; i++) {
       if (!b.indexOf(a[i])) {
         a.pop();
       }
}
Emilio Rodriguez
  • 5,519
  • 4
  • 26
  • 32
0
var a = [4,6,12];
var b = [4,6];

var common = $.grep(a, function(element) {
    return $.inArray(element, b ) !== -1;
});

console.log(common); // returns [4,6];
Sudharsan S
  • 15,058
  • 3
  • 28
  • 49
0

Try this:

var a = [4,6,12];
var b = [4,6];
var i = 0;
for (; i < a.length && i < b.length; i++)
    if (a[i] !== b[i]) {
        a.pop();
        break;
    }
while(i < a.length)
    a.pop();
Ganesh Jadhav
  • 2,780
  • 1
  • 18
  • 31
0
a = a.filter(function(item){ return b.contains(item); });

More on .filter()

Yasser Shaikh
  • 45,616
  • 44
  • 197
  • 276
0

Your second for-loop causes this script to remove everything from a:

1. i = 0, j = 0 => a[0] = 4, b[0] = 4. (4 !== 4) => false, 
2. i = 0, j = 1 => a[0] = 4, b[1] = 6. (4 !== 6) => true, pop first element from a
3. i = 1, j = 0 => a[1] = 6, b[0] = 4. (6 !== 4) => true, pop second elmement from a

So you are popping one element after another from a until a is empty.

Try instead:

var a = [4,6,12];
var b = [4,6];

    for (var i = 0; i < a.length; i++) {
           if (b.indexOf(a[i]) == -1) {
             a.pop();

        }
    }
nanobash
  • 5,293
  • 7
  • 34
  • 56
Jbartmann
  • 1,349
  • 4
  • 23
  • 40