Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ftp_

Thanks

like image 502
user765368 Avatar asked Aug 29 '13 18:08

user765368


People also ask

How do you remove an element from an array based on value?

To remove an object from an array by its value: Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.

How do I remove multiple elements from an array?

Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.


2 Answers

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;
});
like image 170
Artyom Neustroev Avatar answered Sep 24 '22 16:09

Artyom Neustroev


Use a regular expression:

$.each(arr, function (index, value) {
    if (value.match("^ftp_")) {
        arr.splice(index, 1);
    }
});
like image 23
mattytommo Avatar answered Sep 20 '22 16:09

mattytommo