2

I have an array like:

A = ['a', 'del', 'b', 'del', 'c']

how can i remove the elements del such that the result is,

B = ['a', 'b', 'c']

I tried the pop and indexOf method but was unable

3
  • If you say that you tried something and it did not work, then you should show what you have tried and why a question like "Remove a particular element from an array in JavaScript?" did not help you. (I know that this question is about removing multiple elements, whether my referenced one is only about removing one, but the answers target both). If you show your attempt then it would be also possible to tell you what why your did try not work. Commented May 22, 2016 at 6:49
  • Howcome, is this question not duplicate Commented May 22, 2016 at 16:11
  • Possible duplicate of Loop to remove an element in array with multiple occurrences Commented May 23, 2016 at 5:58

1 Answer 1

4

Use filter() for filtering elements from an array

var A = ['a', 'del', 'b', 'del', 'c'];

var B = A.filter(function(v) {
  return v != 'del';
});
 
console.log(B);


For older browser check polyfill option of filter method.


In case if you want to remove element from existing array then use splice() with a for loop

var A = ['a', 'del', 'b', 'del', 'c'];

for (var i = 0; i < A.length; i++) {
  if (A[i] == 'del') {
    A.splice(i, 1); // remove the eleemnt from array
    i--; //  decrement i since one one eleemnt removed from the array
  }
}

console.log(A);

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

3 Comments

filter creates a NEW array, vs splice which modifies the existing array. The difference can be crucial.
@JeremyJStarcher : as per the question , I think he needs to create a new array B , B = ['a', 'b', 'c']
@ubuntuser : glad to help :)

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.