1

I have defined an array like so :

var myArray = {myNewArray: ['string1' , 'string2' , 'string3']};

I want to iterate over the array and delete an element that matches a particular string value. Is there a clean way in jQuery/javascript to achieve this ?

Or do I need to iterate over each element, check its value and if its value matches the string im comparing, get its id and then use that id to delete from the array ?

5

5 Answers 5

3

Here's a JSFiddle showing your solution

var strings = ['a', 'b', 'c', 'd'];
document.write('initial data: ' + strings);
var index = 0;
var badData = 'c';
for(index = 0; index < strings.length; index++)
{
    if(strings[index] == badData)
    {
        strings.splice(index, 1);                 
    }        
}

document.write('<br>final data: '+ strings);​
Sign up to request clarification or add additional context in comments.

Comments

2

JavaScript arrays have an indexOf method that can be used to find an element, then splice can be used to remove it. For example:

var myNewArray = ['A', 'B', 'C'];

var toBeRemoved = 'B';
var indexOfItemToRemove = myNewArray.indexOf(toBeRemoved);
if (indexOfItemToRemove >= 0) {
    myNewArray.splice(indexOfItemToRemove, 1);
}

After that code executes, myNewArray is ['A', 'C'].

1 Comment

This is a bit more efficient than my solution, I think. I'm not sure exactly how indexOf works, though, it may simply be a selection search! :D
1

You can use Array.filter.

filteredArray = myArray.myNewArray.filter(function(el){
  return el === "string";
});

You can check compatibility at Kangax's compat tables.

Comments

0

You could filter the array using $.grep

var myArray = {myNewArray: ['string1' , 'string2' , 'string3']};
myArray = { myNewArray: $.grep(myArray.myNewArray,function(val){
    return val !== "string1";
})};
//console.log(myArray);

Comments

0
my newARR = oldArr.splice( $.inArray( removeItem , oldArr ) , 'deleteThisString');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.