Akai Tanaka Akai Tanaka - 8 months ago 21
Javascript Question

Remove items from based of substring in array jquery

This might seems a very newbie sort of question, but I am struggling with this as of now and seek some help.

Here is a example array in JavaScript

var SelectedFilters = ["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]", "[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];

Now I wish to remove certain items from this array based on a search term, now the search term contains only a part of string such as

var searchTerm1 = 'size'
var searchTerm2 = 'color'

I have already tried the following code, but its not working:

var i = SelectedFilters.indexOf(searchTerm1);
if (i != -1)
SelectedFilters.splice(i, 1);

I have also tried running to through for loop, to iterate on all items, but again search failed as its not able to match 'size' OR 'color'

What I am looking: if searchterm1 is used, the resulted output will be like:


and in case of searchterm2 is used the resulted output should be:


It would be great if anyone can solve this puzzle, I am also trying to find a solution in the meantime.


Your attempt didn't work because .indexOf() on an Array looks for an exact match.

Since according to your question and comment you need to mutate the original Array, you should loop over the array and test each string individually and then call .splice() every time you find one that needs to be removed.

var SelectedFilters =  ["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]", "[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];

var searchTerm1 = 'size' 
var searchTerm2 = 'color'

for (var i = SelectedFilters.length-1; i > -1; i--) {
  if (SelectedFilters[i].startsWith(searchTerm1, 1)) {
    SelectedFilters.splice(i, 1)

document.querySelector("pre").textContent = 
  JSON.stringify(SelectedFilters, null, 2)

The loop used above goes in reverse. This is important since every time we do a .splice(), the array gets reindexed, so if we went forward, we would end up skipping over adjacent items to be removed.

The .startsWith() method checks if the string starts with the given search term. I passed the second parameter a value of 1 so that it starts searching on the second character.