Skip to content Skip to sidebar Skip to footer

Return An Array Of All Indexes Of A Certain Character?

What I'm trying to do should be very simple and I'm not sure why my code isn't working. I'm creating a function that is supposed to return an array of all the indexes of a specifie

Solution 1:

The problem is the line emptyArr.push(str.indexOf(str[i])); and is a problem because String.indexOf() returns the index of the first matched instance of the character.

As noted in the comments, the correction for this problem is to simply use:

emptyArr.push(i);

Which pushes the current index, represented by i, into the array:

var str = "audiueaaudliusa";
var emptyArr = [];

functionabCheck(str) {

  // in the for loop I've made a couple of small changes:// - made 'i' and 'len' local variables,// - used 'len' in order that the 'str.length' wouldn't//   need to be reevaluated on each iteration (it's a tiny,//   tiny optimisation though):for (var i = 0, len = str.length; i < len; i++) {
    if (str[i] === "a") {
      emptyArr.push(i);
    }
  }
  return emptyArr;
}

console.log(abCheck(str)); // [0, 6, 7, 14]

References:

Post a Comment for "Return An Array Of All Indexes Of A Certain Character?"