Ali Ali - 6 months ago 19
jQuery Question

remove all cells that contains specific word in array jquery or Javascript

assume that I have this array:

var fruits = ["Banana-101", "Orange-105", "Apple-110", "Mango-103", "Banana-102", "Banana-104"];


I need to remove all cells that contain word "Banana" so that the output array be like this:

var fruits = ["Orange-105", "Apple-110", "Mango-103"];


how can I do that by using Jquery?

I tried this but it is not works true:

var found = $.inArray(fruit_id, myarray) > -1;
myarray.splice(found, 1);


I saw this question and answer,but in mentioned topic, the answer just removes a cell that contains specific word for example "Banana-101" but my question is how can I remove all cells that have for example "Banana"!

Answer

A solution with Array#filter and String#match.

var fruits = ["Banana-101", "Orange-105", "Apple-110", "Mango-103", "Banana-102", "Banana-104"],
    banana = /banana/i; // regex for banana case insensitive

fruits = fruits.filter(function (a) {
    return !a.match(banana);
});

console.log(fruits);