Satyadev Satyadev - 1 month ago 15
Javascript Question

How to remove number from array based on arguments

I have two arrays like this:

var arr = ["1", "3" , "4"];
var arr2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];


I want to remove numbers from second array based on numbers that are available in first array.

I tried this but I am getting wrong values such as 2,4,6,8:

theButton.onclick = function removePassedInNumbers(arr){
for(var i = 0; i < arr2.length; i++){
if(arr2.indexOf(arr[i])){
arr2.splice(i, 1);
}
}
document.getElementById('myNumber').innerHTML = arr2;
}

<input type="button" id="theButton" onclick="removePassedInNumbers(arr)" value="Click here"/>
<p id="myNumber">hey</p>


Here is the fiddle: https://jsfiddle.net/4hLcanc6/

Where did I go wrong?

Answer

You can update your function with something like this

var arr = ["1", "3" , "4"];
var arr2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];

arr.forEach(function(n){
  var index = arr2.indexOf(n); 
  if(index !== -1) arr2.splice(index, 1);
})

console.log(arr2);

Note: splice will change your array arr2, if you want a new array without changing the original arr2 you should use filter.

Comments