skip to Main Content

I have an array that I wish to return the indexes in a new array if the original array matches a substring.

Currently I am coding it like this:

tv_show = ["bbc1_7.30","bbc1_8.00","itv1_8.40","bbc1_10.00"];
    indexesFromSearch = [];

tv_show.forEach(function(elem, index, array){
    a0 = tv_show[index].substring(0,5);
    if(a0=="bbc1_"){ 
        indexesFromSearch.push(index);
    };
    return indexesFromSearch;
});

alert(indexesFromSearch);

It works fine but just wondered if there is a better way to code it.

Thanks.

4

Answers


  1. You could get the indices and filter with startsWith.

    const
        tv_show = ["bbc1_7.30", "bbc1_8.00", "itv1_8.40", "bbc1_10.00"],
        indices = [...tv_show.keys()].filter(i => tv_show[i].startsWith('bbc1_'));
    
    console.log(indices);
    Login or Signup to reply.
  2. you can use includes like this:

    tv_show = ["bbc1_7.30", "bbc1_8.00", "itv1_8.40", "bbc1_10.00"];
    indexesFromSearch = [];
    
    tv_show.forEach((e, index) => {
      tv_show[index].includes("bbc1_") && indexesFromSearch.push(index);
      return indexesFromSearch;
    });
    
    alert(indexesFromSearch);
    
    Login or Signup to reply.
  3. The simplest way to achieve this is to reduce the array. This is essentially a combination of filter and map.

    const
      tv_show = ['bbc1_7.30', 'bbc1_8.00', 'itv1_8.40', 'bbc1_10.00'],
      indexesFromSearch = tv_show.reduce((acc, val, index) => {
        if (val.startsWith('bbc1_')) {
          acc.push(index);
        }
        return acc;
      }, []);
    
    console.log(indexesFromSearch);

    Here is a concise version with a reusable helper:

    const pushIf = (arr, val, predicate, alt) => {
      if (predicate(val)) arr.push(alt ?? val);
      return arr;
    };
    
    const
      tv_show = ['bbc1_7.30', 'bbc1_8.00', 'itv1_8.40', 'bbc1_10.00'],
      indexesFromSearch = tv_show.reduce((acc, val, index) =>
        pushIf(acc, val, v => v.startsWith('bbc1_'), index), []);
    
    console.log(indexesFromSearch);
    Login or Signup to reply.
  4. You can use reduce and startsWith :

    const tv_show = ["bbc1_7.30", "bbc1_8.00", "itv1_8.40", "bbc1_10.00"];
    
    const indexes = tv_show.reduce((acc, curr, idx) => curr.startsWith("bbc1_") ? [...acc, idx] : acc, []);
    console.log(indexes);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search