Javascript String Get common characters between two String values

Introduction

Write a function `f(a, b)` which takes two strings as arguments and returns a string containing the characters found in both strings (without duplication), in the order that they appeared in `a`.

Remember to skip spaces and characters you have already encountered!

commonCharacters('acexivou', 'aegihobu') => Returns: 'aeiou'

const commonCharacters = function(string1, string2) {
  let duplicateCharacter = '';
  for (let i = 0; i < string1.length; i += 1) {
    if (duplicateCharacter.indexOf(string1[i]) === -1) {
      if (string2.indexOf(string1[i]) !== -1) {
        duplicateCharacter += string1[i];
      }/*from  w ww  .  java 2  s.  c o  m*/
    }
  }
  return duplicateCharacter;
};

console.log(commonCharacters('acexivou', 'aegihobu'))
console.log(commonCharacters('asflkjasfdlk', 'afdlkeope'))



PreviousNext

Related