2

I need to remove all elements in an array that do not contain "IN" in uppercase exactly like that.

How I thought of doing this was to traverse the array with a for loop and write all values that contain IN to another array.

Is there a way I can do it without writing to a new array and just removing those items that don't match from the current array?

Here is the code for how I was planning on doing it:

arrTwo = [];

for(var i = 0; i<arr.length; i++){
    if(arr[i].indexOf('IN') > -1) arrTwo.push[arr[i]];
}
MrGuru
  • 325
  • 5
  • 15
  • There is [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) function defined for the array object which you can use. It will create a new filtered array though – Andrei Jun 13 '14 at 22:39

3 Answers3

13

You can use ES5 filter method:

arr = arr.filter(function(s){
    return ~s.indexOf("IN");
});

And using ES6 arrow functions, it can be simplified to:

arr = arr.filter(s=>~s.indexOf("IN"));
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • This is amazing. What if I wanted to do if it contains IN or NN ? – MrGuru Jun 13 '14 at 22:44
  • @MrGuru Then you can use `~s.indexOf("IN") || ~s.indexOf("NN")`; or regular expressions: `/[IN]N/.test(str)` or `/IN|NN/.test(str)` – Oriol Jun 13 '14 at 22:46
0

Here's a really good thread that has a couple of ways to accomplish this. If you do not delete the element of the array in the correct manner, you that element will be undefined rather than actually deleted. The .spilce() method is what you want to look into.

Deleting array elements in JavaScript - delete vs splice

Community
  • 1
  • 1
mwilson
  • 12,295
  • 7
  • 55
  • 95
0

I would do it using the splice() method:

var testArray = [ 'this one contains IN', 'this one does not' ];

function filterArray ( arr ) {
    var i = arr.length;
    //-- Loop through the array in reverse order since we are modifying the array.
    while (i--) {
        if (arr[i].indexOf('IN') < 0) {
            //-- splice will remove the non-matching element
            arr.splice(i, 1);
        }
    }
}

filterArray( testArray );

document.body.innerText = JSON.stringify(testArray);

JSFiddle: http://jsfiddle.net/5DW8L/1/

Robert Messerle
  • 3,022
  • 14
  • 18