Peyo33
Peyo33

Reputation: 157

How to find the index of the 1st occurence of a condition ( > 0 in my case) in an array in javascript

All in the title. I tried so many things I can't even count. My goal is to count how many 0 are before the 1st occurrence of a number which is > 0 in numArr, so I can work with that later in my code. I truly have no clue how to do this properly.

My code so far :

function incrementString(strng) {
  // loop though the splitted array
  let newArr = strng.split('');
  let numArr = [];
  let lettersArr = [];
  for (let i = 0; i < newArr.length; i++) {
    if (isNaN(newArr[i]) === false) {
      numArr.push(parseInt(newArr[i]));
    } else {
      lettersArr.push(newArr[i]);
    }
  }

  let newNbr = parseInt(numArr.join('')) + 1;
  let result = lettersArr.join('') + newNbr;
  console.log(numArr, result);
}

incrementString('foobar0100');

Upvotes: 1

Views: 75

Answers (3)

mplungjan
mplungjan

Reputation: 177692

This will work in all browsers and has no weird syntax - assuming I understood your question correctly

var incrementedString = 'foobar0100'.replace(/[1-9]/, function(num, pos, string) {
  return (++num);
});
console.log(incrementedString)

Upvotes: 0

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

You can first convert your string to an array of characters (you can use the spread syntax for this) and then use findIndex to find the index of the first character that fulfils your condition:

const text = 'foobar0100';
const index = [...text].findIndex((character) => Number(character) > 0);

console.log(index);

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386540

You could take Array#findIndex with a regular expression for finding the characters '1' ... '9'.

function findNumber(string) {
    return Array.from(string).findIndex(s => /[1-9]/.test(s));
}

console.log(findNumber('foobar0100'));

Upvotes: 3

Related Questions