0

I am trying to remove all the even numbered items from my array with this code:

var myArray = [1,2,3,4,5,6];  

myArray.forEach(function(item) {    
  if (item%2 == 0) {
    myArray.splice(item); 
  } 
}); 

I think where im getting it wrong is with the splice?

4 Answers 4

4

you can do like this :

var myarray = [1,2,3,4,5,6]
  filtered = myarray.filter(function(el, index) {
    return index % 2 === 1;
  });

output : [2, 4, 6]

Sign up to request clarification or add additional context in comments.

Comments

3

You should do it this way:

var myArray = [1,2,3,4,5,6];  

myArray.forEach(function(item, x) {    
  if (item%2 == 0) 
    myArray.splice(x, 1); // Remove 1 item from index x
}); 

Fiddle

Or the better way to use .filter (IE8+)

var myArray = myArray.filter(function(item) {    
      return item % 2 ==0  ?  false  :  true; // Return false if item is even and true other way round.
}); 

Fiddle

Comments

2

yes, splice is done by index

var myArray = [1,2,3,4,5,6];  

myArray.forEach(function(item) {    
  if (item%2 == 0) {
   var index = myArray.indexOf(item); 
    myArray = myArray.splice(index,1); 
  } 
}); 

Comments

2

filter() would be better

  var arr = myArray.filter(function(item) {    
      return item % 2 ==0  ?  true  :  false;
   }); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.