Finding matching string from javascript array

前端 未结 4 1335
失恋的感觉
失恋的感觉 2021-02-08 07:29

I have one array of strings. I need to find all strings starting with a key. for eg: if there is an array [\'apple\',\'ape\',\'open\',\'soap\'] when searched with

4条回答
  •  名媛妹妹
    2021-02-08 08:11

    function find(key, array) {
      // The variable results needs var in this case (without 'var' a global variable is created)
      var results = [];
      for (var i = 0; i < array.length; i++) {
        if (array[i].indexOf(key) == 0) {
          results.push(array[i]);
        }
      }
      return results;
    }
    

提交回复
热议问题