Skip to content Skip to sidebar Skip to footer

Remove All Items In Array That Start With A Particular String

Hi let's say that I have an array like this in javascript: var arr = ['ftp_text_1', 'abc_text_2', 'ftp_text_3']; How do I remove from all the strings from my array that start with

Solution 1:

Simply use Array.filter:

arr = arr.filter(function (item) {
   return item.indexOf("ftp_") !== 0;
});

Edit: for IE9- support you may use jQuery.grep:

arr = $.grep(arr, function (item) {
   return item.indexOf("ftp_") !== 0;
});

Solution 2:

Use a regular expression:

$.each(arr, function (index, value) {
    if (value.match("^ftp_")) {
        arr.splice(index, 1);
    }
});

Solution 3:

The index position of the element shifts up as a element is deleted from the list hence some elements may not delete from the list.

So the best practice is to delete the list from the end .

for(var i=arr.length-1 ; i>=0;i--){
   if(arr[i].includes("ftp_"){
      arr.splice(i, 1);
   }
}

Solution 4:

Use temp array to store your required string.

for(i=0;i<are.length;i+=) {
  if(!arr[i].startesWith('ftp_')){
    temp[j]=arr[i];
    j++:
  }
  arr=temp;
}

Post a Comment for "Remove All Items In Array That Start With A Particular String"