1

Hi i need to remove the array from another array.Below is the code that i had tried

var dummyObj = ["item1"];
var dummyArray = [ "item1", "item3", "item2"];


var data1=removeFromArray(dummyArray, dummyObj);

console.log("data1"+data1)

function removeFromArray(array, item)
{
while((index = array.indexOf(item)) > -1)
array.splice(index,1);
return array
}

below is my output

item1,item3,item2

But the required output is

item3,item2

Dont know where i am going wrong.Any help regarding this will be much helpful

user2882721
  • 221
  • 1
  • 3
  • 12

4 Answers4

0

The problem with your code is that, item is actually dummyObj which is an array and that does not exist in dummyArray. That is why it fails to remove it.

You can use Array.prototype.filter, like this

dummyArray = dummyArray.filter(function(currentItem) {
    return dummyObj.indexOf(currentItem) === -1;
});

console.log(dummyArray);    // [ 'item3', 'item2' ]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

Check out Underscore.js, a javascript utility belt:

http://underscorejs.org/#difference

html_programmer
  • 18,126
  • 18
  • 85
  • 158
0

You have few errors there:

while((index = array.indexOf(item)) > -1)

Should be

while((index = array.indexOf(item) > -1)

Also you need to loop through both dummyArray and dummyObj, because your item variable is actually dummyObj, so you need to loop through it to check each element separately.

dkasipovic
  • 5,930
  • 1
  • 19
  • 25
0

You argument item is an is an array object so you have to use it like item[0]

 while((index = array.indexOf(item[0])) > -1)

if dummyObj contains for than one values then you have to add an extra loop

function removeFromArray(array, item)
{
for(var j=0;j<item.length;j++){
while((index = array.indexOf(item[j])) > -1)
array.splice(index,1);

}
return array
}
Sarath
  • 608
  • 4
  • 12