How to search a character in a set of javascript strings

Asked

Viewed 41 times

4

I have a set with certain strings, it is a vector, need to be done searches for characters in this set.

Case:

  • Be it V my set of strings contemplated by: ["ana", "paula", "cris", "voa", "karmanguia"];
  • Be it P my research, I wish it to be checked on the whole V the occurrence of P in these strings.

I wish to return the confirmation of the occurrence of such character and where.

1 answer

4


const V = ["ana", "paula", "cris", "voa", "karmanguia"];
const P = 'a';

const res = V.reduce((found, string, i) => {
  const stringHasLetter = string.includes(P); // para saber se essa string tem a letra pretendida
  if (!stringHasLetter) return found;
  // para saber quais as posições da letra dentro da string
  const letterPositions = string.split('').map(
    (l, idx) => l == P && idx
  ).filter(nr => typeof nr == 'number').join(', ')
  return found.concat({
    vIndex: i,
    letterPositions: letterPositions
  });
}, []);

console.log(res);

The idea is to search each string and return the results in each string as well.

  • Thanks and congratulations Sergio, just what I need is there!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.