Error using split() method

Asked

Viewed 38 times

0

I’m solving a problem where I have to take a person’s first and last name and I have to return the initials of it. As I am a beginner in the area, there are certainly other ways to resolve this issue. Regardless of the other ways, I’d like to understand what I did wrong, mistake I get:

Uncaught Typeerror: firstName.split is not a Function at pickInitials (script.js:18) at script.js:24

in the solution I tried below:

     const pickInitials = function (name) {
    
      const NameArray = name.split(' '); // Convertendo string recebida para array com dois elementos
      
      const firstName = []; // Criando outras arrays para armazenar elementos da conversão anterior
      const lastName = [];
    
      firstName.push(NameArray[0]); // Adicionando primeiro e segundo nome nas arrays criadas
      lastName.push(NameArray[1]);
    
      const firstNameArray = firstName.split(''); // Dividindo arrays criadas em outras arrays, agora por caractere, aqui ocorre o erro
      const lastNameArray = lastName.split('');
    
      return console.log(`${firstNameArray[0]}.${lastNameArray[0]}`); // Retornando primeiro caractere de cada array
    }
    
    pickInitials('Diego Oliveira');
    pickInitials('Sam Harris');
    pickInitials('Patrick Feeney');

  • in which case, if I understood the code correctly, it should be: const firstNameArray = firstName[0].split('')

1 answer

1


Would not be firstName[0].split(''); instead of firstName.split(''); and lastName[0].split(''); instead of lastName.split('');, for this case?

In this way:

     const pickInitials = function (name) {
    
      const NameArray = name.split(' '); // Convertendo string recebida para array com dois elementos
      
      const firstName = []; // Criando outras arrays para armazenar elementos da conversão anterior
      const lastName = [];
    
      firstName.push(NameArray[0]); // Adicionando primeiro e segundo nome nas arrays criadas
      lastName.push(NameArray[1]);
    
      const firstNameArray = firstName[0].split(''); // Dividindo arrays criadas em outras arrays, agora por caractere, aqui ocorre o erro
      const lastNameArray = lastName[0].split('');
    
      return console.log(`${firstNameArray[0]}.${lastNameArray[0]}`); // Retornando primeiro caractere de cada array
    }
    
    pickInitials('Diego Oliveira');
    pickInitials('Sam Harris');
    pickInitials('Patrick Feeney');

Turns out that here firstName.push(NameArray[0]); you added an element to the array firstName, logo to access this element that is in index 0, you need the [0] before the method .split(''). The same goes for the array lastName.

The error is due to the fact that split is a string method and not an array method.

  • Thank you very much, I saw that you made some corrections to my question and I thank you, I arrived now and I’m half lost, rs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.