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 ?

Dave Newton
  • 152,765
  • 23
  • 240
  • 286
user701254
  • 3,855
  • 7
  • 37
  • 52

5 Answers5

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);​
Codeman
  • 11,457
  • 8
  • 48
  • 89
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'].

csd
  • 1,694
  • 10
  • 18
  • 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 – Codeman Jun 19 '12 at 22:40
1

You can use Array.filter.

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

You can check compatibility at Kangax's compat tables.

Alexander
  • 22,498
  • 10
  • 56
  • 73
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);
Kevin B
  • 92,700
  • 15
  • 158
  • 170
0
my newARR = oldArr.splice( $.inArray( removeItem , oldArr ) , 'deleteThisString');
Derek 朕會功夫
  • 84,678
  • 41
  • 166
  • 228
Frank Visaggio
  • 3,442
  • 8
  • 29
  • 70