javascriptarraystypescript

Javascript - Elements added into an array not in correct place


I have a little problem to add some element in place into an array. I'm trying to add after the last lowercase letter that is z the uppercase letter of the alphabet. I'm using this code. I've noticed that the lower char z is added after all the uppercase letters are added into the array, also the first two uppercase letters are repeated before the lower z is added. How I can fix this?

onst splitMatrix = async (inputMatrix: string) => {
  let splitted: Array<string> = inputMatrix.split(''); 
  let index: number = splitted.indexOf("z");
  //let uppercaseChars: Array<string> = [];
  //
  index + 1;
  for (let i = 0; i < 23;i++){
    let char: string = splitted[i].toUpperCase();
    //uppercaseChars.push(char);
    splitted.splice(index + i, 0, char);
    console.log(char)
  }
  //console.log(uppercaseChars)
  //console.log(splitted)
  return splitted;
}

This is what I will have as result of the code

[
  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
  'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
  'u', 'w', 'x', 'y', 'A', 'B', 'C', 'D', 'E',
  'F', 'G', 'H', 'I', 'L', 'M', 'N', 'O', 'P',
  'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'A',
  'z', '0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', '@', '-', '_', '+', '*', '(', ')',
  ',', '.', '#'
]

My idea is to add a control on the chars to avoid duplicated entries into the array, but I'm open to any tips to solve this. Thank you


Solution

  • Iterate the array, stop at the original length (len), and push the uppercased letters to the end:

    const splitMatrix = inputMatrix => {
      const splitted = inputMatrix.split(''); 
      
      const len = splitted.length;
      
      for (let i = 0; i < len; i++){
        splitted.push(splitted[i].toUpperCase());
      }
    
      return splitted;
    }
    
    const result = splitMatrix('abcdefghijklmnopqrstuvwxyz');
    
    console.log(result);

    Another option is to map the lowercase characters array to an array of uppercase letters, and then concat it with the lowercase array:

    const splitMatrix = inputMatrix => {
      const lowerCase = inputMatrix.split(''); 
      
      return lowerCase.concat(
        lowerCase.map(l => l.toUpperCase())
      );
    }
    
    const result = splitMatrix('abcdefghijklmnopqrstuvwxyz');
    
    console.log(result);