How to search for a character in a set of javascript strings

4

I have a set with certain strings, it's a vector, I need to do character searches in this set.

Case:

  • Be V my set of strings contemplated by: ["ana", "paula", "cris", "voa", "karmanguia"];
  • Be P my search, I want to check in the set V the occurrence of P in these strings.

I want you to return confirmation of the occurrence of such a character and where.

    
asked by anonymous 15.09.2017 / 15:12

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.

    
15.09.2017 / 15:27