1

Apologies if this is a duplicate, but I can't seem to find the solution. I am trying to find a specific string pattern in an array. I want to find all values in data that contain 'underscore r underscore'. I then want to create a new array that contains only those keys and values.

var data = ["something", "bar_r_something"];
var resultArray = new Array();    
for (var i = 0; i < data.length; i++) {
    var bar = /_r_/;
    if ($.inArray(bar, data[i].length) > 0)
    {
       console.log("found _r_");
       resultArray.push(data[i]);
    }
};

I just can't seem to get that $.inArray to work, it seems to always kick out -1.

Greg
  • 481
  • 1
  • 5
  • 21
Bwyss
  • 1,736
  • 3
  • 25
  • 48
  • possible duplicate of [Javascript - search for a string inside an array of strings](http://stackoverflow.com/questions/5424488/javascript-search-for-a-string-inside-an-array-of-strings) – JJJ Nov 04 '13 at 09:56

2 Answers2

5
var data = ["something", "bar_r_something"];
var resultArray = new Array();
for (var i = 0; i < data.length; i++) {
    var bar = /_r_/;
    if (bar.test(data[i])) {
        alert("found _r_");
        resultArray.push(data[i]);
    }
};

console.log(resultArray);

Here you go, it doesn't use $.inArray, but Regex instead, hope that's cool!

EDIT

If you wanted to go a bit more fancy, you can use JavaScript's filter method like so:

var data = ["something", "bar_r_something"];
var resultArray = data.filter(function(d){
    return /_r_/.test(d);
});

console.log(resultArray);
benhowdle89
  • 36,900
  • 69
  • 202
  • 331
2

I think what you are looking for is $.grep(). Also $.inArray() does not test the values against a regex, it tests for equality.

var regex = /_r_/
var resultArray  = $.grep(data, function(item){
    return regex.test(item)
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531