Advertisement
TZinovieva

Serialize String JS Fundamentals

Mar 9th, 2023 (edited)
868
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function serializeString(arr) {
  2.     let str = arr[0];
  3.     let charPositions = {};
  4.  
  5.     // Iterate over the characters in the string and keep track of their positions
  6.     for (let i = 0; i < str.length; i++) {
  7.         let char = str[i];
  8.         if (!charPositions[char]) {
  9.             charPositions[char] = [i];
  10.         } else {
  11.             charPositions[char].push(i);
  12.         }
  13.     }
  14.  
  15.     // Iterate over the charPositions object and format the output string
  16.     let output = '';
  17.     for (let char in charPositions) {
  18.         let positions = charPositions[char];
  19.         output += `${char}:${positions.join('/')}\n`;
  20.     }
  21.     console.log(output);
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement