1

I have

var a =[1 , 2, 3, 4, 5]
var b = [2, 3]

Now I want to remove b from a using inArray

if($.inArray(b, a) === 1)
  a.remove(b);

is this right ? cause when i console a , it hasnt changed

jyoti
  • 341
  • 1
  • 4
  • 10
  • 2
    Array doesn't have a method remove. You need to get the index of b and use splice. Check out: http://stackoverflow.com/questions/5767325/remove-specific-element-from-an-array for details. – scrappedcola Feb 04 '14 at 18:47
  • 2
    in your case `$.inArray(b, a)` will always be -1 because `b` is itself an array. you can't literally remove `b` from `a` because `b` isn't in `a`. – Kevin B Feb 04 '14 at 18:55

3 Answers3

3

Try this this may help you

function arr_diff(a1, a2)
{
  var a=[], diff=[];
  for(var i=0;i<a1.length;i++)
    a[a1[i]]=true;
  for(var i=0;i<a2.length;i++)
    if(a[a2[i]]) delete a[a2[i]];
    else a[a2[i]]=true;
  for(var k in a)
    diff.push(k);
  return diff;
}
var a = [1,2,3,4,5,6]
var b = [2,3]
console.log(arr_diff(a,b));
Rohit Subedi
  • 562
  • 3
  • 13
2

There are several errors here. First of all, jQuery's inArray searches for elements, not subArrays. So you might conceivably imagine that you would find that

$.inArray([2, 3], [[1, 2], [2, 3], [3, 4], [4, 5]])

would yield 1, but in fact even that won't work, because it follows the Array.prototype standards and compares with reference equality.

It certainly won't find the array [2, 3] as an element of [1, 2, 3, 4, 5].

Next, if it did happen to find that array, Array.prototype has no remove function.

You might want to look at Array.prototype.splice().

Scott Sauyet
  • 37,179
  • 4
  • 36
  • 82
0

Here is one option (arraysEqual() borrowed from this answer):

function arraysEqual(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false;
    if (a.length != b.length) return false;

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

for (var i = 0; i <= a.length - b.length; i++) {
    var slice = a.slice(i, i + b.length);
    if (arraysEqual(slice, b)) {
        a.splice(i, b.length);
    }
}

This loops through a comparing slices of a to b, and removing that slice when a match is found.

Community
  • 1
  • 1
Andrew Clark
  • 180,281
  • 26
  • 249
  • 286