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

156
Vistas
cant able to remove common letters from two strings in javascript

I need to remove common letters from both the strings. But, some of the letters get removed.some of them not. In this example, a is common in both the strings.but not get removed. Could you tell the mistake what I did?

var a = "car"
var b = "karthic"
var c = a.length;
var d = b.length;

for (var i = 0; i < c; i++) {
  for (var j = 0; j < d; j++) {
    if (a[i] === b[j]) {
      a = a.slice(0, i) + a.slice(i + 1);
      b = b.slice(0, j) + b.slice(j + 1);
      break;
    }
  }
}

console.log(a + " " + b);

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

First find all common letters, then remove them from each string:

var a = "car"
var b = "karthic"
var c = a.length;
var d = b.length;

var commonLetters = [];

for (var i = 0; i < c; i++) {
  for (var j = 0; j < d; j++) {
    if (a[i] === b[j]) {
      commonLetters.push(a[i]);
    }
  }
}

var regex = new RegExp('[' + commonLetters.join('') + ']', 'g')

a = a.replace(regex, '');
b = b.replace(regex, '');

console.log('A: ' + a, 'B: ' + b, commonLetters);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can convert both strings to a set, find the difference and then filter (include) any characters that are included in the difference.

Access to a Set is O(1) which is better than your (worst-case) O(n^2) loop. You will have to filter all of the characters in each string so this will be O(n) complexity as your base-case.

// Reusable
const strSet = (str) => new Set(str.split(''));
const setDiff = (a, b) => new Set(Array.from(a).filter(item => !b.has(item)));
const prune = (str, set) => str.split('').filter(x => set.has(x)).join('');

// Specific
const a = 'car', b = 'karthic';
const diff = setDiff(strSet(b), strSet(a));
const a1 = prune(a, diff), b1 = prune(b, diff);

console.log(`a1 = "${a1}"\nb1 = "${b1}"`);

about 4 years ago · Juan Pablo Isaza Denunciar

0

let a = "car"
let b = "karthic";

let resultA = a.split('').filter((elem) => b.indexOf(elem) == -1).join('');
let resultB = b.split('').filter((elem) => a.indexOf(elem) == -1).join('');

console.log(resultB);
 console.log(resultA);

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