Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!