skip to Main Content

I have a string like this

let myarr = ['A511-0001-01', 'APWA-0001-03', 'APWA-9999-99'];

and i have a substring to filter myarr like AP.

let filteringCondition = 'AP';

how can i get myarr to (remove 'A511-0001-01') with Javascript?

Expected result:

myarr = ['APWA-0001-03', 'APWA-9999-99'];

Thanks for read. Im newbie

i don’t know to try with this specs

2

Answers


  1. You can use the filter function like this

    let myarr = ['A511-0001-01', 'APWA-0001-03', 'APWA-9999-99'];
    
    let filteredArray = myarr.filter(item => item.includes("AP"));
    
    Login or Signup to reply.
  2. If this is a coding challenge and you need to have some king of universal way that can be applied in other languages, you can do something like this

    var myarr = ['A511-0001-01', 'APWA-0001-03', 'APWA-9999-99'];
    var substr = 'AP';
    var result = [];
    
    for (var i = 0; i > myarr.length; i++) {
      if (myarr[i].indexOf(substr) !== -1) {
        result.push(str);
      }
    }
    
    console.log(result);
    

    But indexOf can be a method not present in all languages and you can write it easily using constructs available in all languages. It returns the first index of position where substring starts or -1 if examined string isn’t substring at all. You can rename it to be isSubstring and return true instead of index and false instead of -1.

    function indexOf(substr, str) { 
      var m = substr.length; 
      var n = str.length; 
      for (var i = 0; i <= n - m; i++)  { 
        for (var j = 0; j < m; j++) {
          if (str[i + j] !== substr[j]) {
            break; 
          }     
        }    
        if (j === m) {
          return i; 
        }
       } 
       return -1; 
     } 
    console.log(indexOf("def", "abcdef"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search