2

I have a array in javascript containing "aassd,v_value1,asadds,v_value2, asddasd...", and I need extract the values that begin with v_ in a new array.

I used the next function to get the values, but only get the first value.

function search (array,string) {

    var arr= [];

    for (var i=0; i<array.length; i++) {
        if (array[i].match(string)){

          arr.push(i)

          return arr;
        }  
    }
      return -1;
  }

 search(array,'v_')

Thanks.

Sebas_Sx
  • 21
  • 3

3 Answers3

2

You should use .filter() method as below:

function search (array,string) {
  return array.filter(function (val) {
    return val.substr(0, string.length) === string;
  });
}

The filter() method returns items of array which fulfills the condition in the callback function

Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
1

I think below might work. Just string match and push to new array if found.

var arr = ['aassd','v_value1','asadds','v_value2','asddasd'];
var newArr = []


substring = "v_";

for (var i = 0; i < arr.length; i++) {
    if (arr[i].search(substring) === 0) {
      newArr.push(arr[i]);
    }
}

alert(newArr);
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
  • index of should not be used as it will return values like "asdasdv_asdasd" also which is wrong. – cafebabe1991 May 14 '16 at 15:21
  • I just dropped the code into the snippet tool and it works fine. What do you mean index should not be used? – Ronnie Royston May 14 '16 at 15:31
  • I meant code does works fine, but try putting these items in the array "ararav_asasd". Now v_ does exist and so index will be greater that -1 , hence it will be put into the array but it should not be as it does not "START with" the pattern as asked in the question – cafebabe1991 May 14 '16 at 15:33
0
function search (array,string) {

    var arr= [];

    for (var i=0; i<array.length; i++) {
        //Do not use MATCH here as you need values that STARTS WITH "v_", match will give you values like this asdasdav_asdasda also.
        if (array[i].startsWith(string)){
          //instead of this 
          //arr.push(i)
          //use this , the above will push the index, this will push the VALUE(as asked in the question)
          arr.push(array[i])

          //remove this: as this breaks on the first true condition , hence you get one value.
          //return arr;
        }  
    }
      return arr;
  }

The Mistakes

  1. Do not use MATCH for it will return values with the pattern anywhere in the string. Use startsWith instead
  2. Return outside the loop as it ends the loop when it matches the first time and hence you get only the first item
  3. You should push the value not the index as asked in the question. So do this arr.push(array[i])
cafebabe1991
  • 4,928
  • 2
  • 34
  • 42