首頁 > web前端 > js教程 > JavaScript 中字元與字串重疊

JavaScript 中字元與字串重疊

Mary-Kate Olsen
發布: 2024-10-22 06:28:03
原創
748 人瀏覽過

Character overlap with strings in JavaScript

寫一個函數,它接受兩個字串並顯示(不帶雙精確度)出現在任一字串中的字元。

解決方案

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"));
登入後複製

結果

> computer
> frontedvlpm
> mivrog
> praxet
> stone
> rescu
登入後複製

以上是JavaScript 中字元與字串重疊的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板