Shan
Shan

Reputation: 23

How to remove an element in array if it has particular characters?

I want to remove the elements from the array if it contains particular values.

var array = [[email protected], www.hello.com, [email protected]];

I want to remove the al elements which has @ signs. when I alert the array I need only www.hello.com.

Upvotes: 0

Views: 46

Answers (4)

kevin ternet
kevin ternet

Reputation: 4612

You can also loop the input array and push element that match into the output array

var array = [
'[email protected]',
'www.hello.com',
'[email protected]'];
var newArray = [];
array.forEach(x => { 
  if(x.indexOf('@') === -1) 
     newArray.push(x);
});
console.log(newArray)

Upvotes: 0

brk
brk

Reputation: 50316

Avoid deleting/changing index of elements of array inside a loop. This is because the array is being re-indexed when you do a .splice(), which means you'll skip over an index when one is removed,

Instead you can filter out the element and get a new array which match your criteria

var array = [
'[email protected]',
'www.hello.com',
'[email protected]'];
var newArray = array.filter(function(item){  
    return item.indexOf('@') ==-1
})
console.log(newArray)

DEMO

Upvotes: 0

TrojanByAccident
TrojanByAccident

Reputation: 227

One way to do this is to use a Regular Expression, along with another array, like so:

var array = ['[email protected]', 'www.hello.com', '[email protected]'];
var array2 = [];
for (var i = 0; i < array.length; i++) {
  if (!(/@/.test(array[i]))) {
    array2.push(array[i]);
  };
};
alert(array2);

Upvotes: 0

Paul Z.
Paul Z.

Reputation: 905

array.forEach(function(element, key) {
    if (element.indexOf('@') !== -1) {
        array.splice(key, 1);
    }
});

Upvotes: 1

Related Questions