1

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

Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157
ubuntuser
  • 35
  • 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?](http://stackoverflow.com/questions/5767325)" 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. – t.niese May 22 '16 at 06:49
  • Howcome, is this question not duplicate – Redu May 22 '16 at 16:11
  • Possible duplicate of [Loop to remove an element in array with multiple occurrences](http://stackoverflow.com/questions/20733207/loop-to-remove-an-element-in-array-with-multiple-occurrences) – t.niese May 23 '16 at 05:58

1 Answers1

3

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);
Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157