Home > Web Front-end > JS Tutorial > body text

Character overlap with strings in JavaScript

Mary-Kate Olsen
Release: 2024-10-22 06:28:03
Original
645 people have browsed it

Character overlap with strings in JavaScript

Write a function that takes two strings and displays, without doubles, the characters that appear in either one of the strings.

Solution

function characterOverlap(array1, array2) {
  let occurrence = {};

  let str = array1.concat(array2);

  // find the count of each character
  Array.from(str).forEach((char) => {
    let currentCount = occurrence[char] || 0;
    occurrence[char] = currentCount + 1;
  });

  // return the keys which is the individual character and join.
  const result = Object.keys(occurrence);

  return result.join("");
}

console.log(characterOverlap("computer", "circuitemtop"));
console.log(characterOverlap("frontend", "development"));
console.log(characterOverlap("mivrog", "gormiv"));
console.log(characterOverlap("praxet", "xetpar"));
console.log(characterOverlap("stone", "tones"));
console.log(characterOverlap("rescue", "secure"));
Copy after login

Result

> computer
> frontedvlpm
> mivrog
> praxet
> stone
> rescu
Copy after login

The above is the detailed content of Character overlap with strings in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!