Repeated letter contained within the JavaScript String vector


Good afternoon, how could I do so that within a String array I can detect which letters are repeated within themselves?

For example, if I have the contained vector = ["hello", "piano", "triangle"]; can return an array result = ["o", "a"]; which are the 3 letters that are present in each String, I tried with for but it does not come out, some help please, thanks

This code I tried:

    var datos= ["hola", "piano", "triangulo"];
    var resultado[];

    for(int i=0;i<datos.length;i++){
    char A[] = datos[i];
        var a=0;
            char B[] = datos[i+1];

            for(int j=0;j<A.length;j++){
asked by Kako 25.01.2018 в 23:33

1 answer


The truth is that I can not follow your code.

In addition, the syntax char variable[] does not serve to declare an array of characters in javascript. Javascript is a non-typed language, the type of the variable is not indicated, so these can contain any type of value.

Here is a possible solution:

function repetidos(palabras){
  // Si no se pasa array o se pasa uno de longitud 0 devuelve null
  if (!palabras || !palabras.length) return null;
  // Cogemos los caracteres de la primera palabra
  var first = contenido[0].split('');
  // Obtenemos los caracteres de la primera palabra que están
  // presentes en todas
  return first.filter(
    (c, i) =>
      first.indexOf(c) === i // es la primera ocurrencia del carácter
      && contenido.every(x=> x.indexOf(c) >= 0)); // y está en todas

var contenido= ["hola","piano","triangulo"];


The code takes the first word and converts it to an array of characters by calling the split method with an empty string.

Then use the filter method to catch only the characters that appear for the first time (the indexOf method on the character returns the current index: first.indexOf(c) === i ) and they are found on all the words in the array (use every to verify that all elements of the array satisfy the condition that they contain the character: x.indexOf(c) >=0 .

answered by 26.01.2018 в 00:08