Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
How to get word from array which character in it appearing exactly two times

I have array contains strings. I have to read the words one by one and output words which has any character in it appearing exactly two times. But my code also show 3 or more same character also. How can I output the words which only character appearing two times ? For example not showing : "aaaa" or "aaab"

const words = [
  "asdf",
  "fdas",
  "asds",
  "d fm",
  "dfaa",
  "aaaa",
  "aabb",
  "aaabb"
];

function checkString(text,index){
    if((text.length - index) == 0 ){ //stop condition
        return false; 
    }else{
        return checkString(text,index + 1) 
        || text.substr(0, index).indexOf(text[index])!=-1;
    }
}

// example Data to test

for(var idx in words){
    var txt = words[idx];
  
  if(checkString(txt,0)) {
    console.log(txt);
  }
  
}

const words = [
  "asdf",
  "fdas",
  "asds",
  "d fm",
  "dfaa",
  "aaaa",
  "aabb",
  "aaabb"
];

/*
Output have to be :
asds
dfaa
aabb
aaabb
*/
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

const words = [ "asdf", "fdas", "asds", "d fm", "dfaa", "aaaa", "aabb", "aaabb" ];

function checkString(text) {
  //create a map to store the frequency of characters
  let map = new Map();
  for(let ch of text){
    if(map.has(ch)){
      map.set(ch, map.get(ch)+1);
    }else{
      map.set(ch, 1);
    }
  }
  
  //now check if frequency of any character is equal to 2
  return [...map.values()].some(x => x == 2);
}

// example Data to test

for (let txt of words) {
  if (checkString(txt)) {
    console.log(txt);
  }
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can build an object mapping letters in your input string to its occurrences in it, then filter the letters based on whether they appear twice:

const checkString = (inputString) => {
  // Build an empty object
  const occurrences = {};
  for (let char of inputString) {
    // For each character in the input string, add one to its occurrence count
    // If it has never appeared until now, occurrences[char] + 1 will evaluate
    // to NaN, and Nan || 1 is 1
    occurrences[char] = occurrences[char] + 1 || 1;
  }

  // Get the characters appearing in the string
  const charsInInputString = Object.keys(occurrences);
  // Extract only the characters appearing exactly twice
  const charsAppearingTwice = charsInInputString.filter(
    (char) => occurrences[char] === 2
  );
  // Return true if there is at least one such character
  return charsAppearingTwice.length > 0;
};

Your final array of correct words would then be words.filter(checkString).

If you want to format the words to display as a single string, with a space separator, you can use the .join method:

const checkedWords = words.filter(checkString).join(" "); // = asds dfaa aabb aaabb
about 4 years ago · Juan Pablo Isaza Denunciar

0

A better way to do it is to write a function that takes a string and counts how many of each character it contains, and then check if there's a character that appears exactly two times.

Something along the lines of

function checkString(text){
    const charAppearances = {};
    text.split('').forEach( character => {
       charAppearances[character] = (charAppearances[character] || 0) + 1
   })
    return Object.values(charAppearances).includes(2);
}

The purpose of charAppearances is to count how many times a character appears, so for example for the string 'asdf' it will be {a: 1, s: 1, d:1, f:1}

The forEach section iterates over the characters of the string and updates the count of the current character (The charAppearances[character] = (charAppearances[character] || 0) + 1 means "If character exists in charAppearances, add 1 to it, otherwise add 1 to 0, which will result 1)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda