Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

67
Visualizações
Array Parsing & String Construction in Javascript

I think I am close but I would to get your feedback to solve this using a derivative of the code I have already created, I pass the following tests, but I am struggling to pass the final test as I need to return two middle names abbreviated, and at the moment I can only return the first. The tests below show the function and parameters passed, and the expected result its the last ione I am struggling with. I would appreciate your expert advice. Kind regards, Jon

Test.assertEquals(initializeNames('Jack Ryan'), 'Jack Ryan', '');
Test.assertEquals(initializeNames('Lois Mary Lane'), 'Lois M. Lane', '');
Test.assertEquals(initializeNames('Dimitri'), 'Dimitri', '');
Test.assertEquals(initializeNames('Alice Betty Catherine Davis'), 'Alice B. C. Davis', '')

function initializeNames(name) {

  let seperateNames = name.split(' ');
  let output = "";

  if (name.length = 2) {
    output = name;
  }

  for (let i = 1; i < seperateNames.length - 1; i++) {

    output = seperateNames[i];
    let abvName = output.substring(0, 1) + '.';
    output = seperateNames[0] + ' ' + abvName + ' ' + seperateNames.slice(-1);
  }

  return output;
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This if condition is useless. Because = is assignment and == is equality check.

if (name.length = 2) {
    output = name;
  }

Also I believe you wanted to check the length of seperateNames array. You already know what to do if length is less than equal to 2.

But if it is not then you need your loop and extra calculation.

Have a look at below code which starts with

  1. the first name, and

  2. add the abvName, and then

  3. the last name

console.log(initializeNames('Jack Ryan'));
console.log(initializeNames('Lois Mary Lane'));
console.log(initializeNames('Dimitri'));
console.log(initializeNames('Alice Betty Catherine Davis'));

function initializeNames(name) {

  let seperateNames = name.split(' ');
  let output = "";
  
  if (seperateNames.length <= 2) {
    output = name;
  }
  else{ output = seperateNames[0];
  for (let i = 1; i < seperateNames.length - 1; i++) {
    let currentOutput = seperateNames[i];
    let abvName = currentOutput.substring(0, 1) + '.';
    output = output + ' ' + abvName + ' ';
  }
  output += seperateNames[seperateNames.length - 1];
  }
  return output;
}

Note : x += b; is the same as x = x + b;

about 4 years ago · Juan Pablo Isaza Relatório

0

function initializeNames(name) {
  const [first, ...rest] = name.split(' ');
  return !rest 
    ? first
    : rest.length === 1 
    ? name 
    : rest.length === 2
    ? `${first} ${rest[0][0]}. ${rest[1]}`
    : `${first} ${rest[0][0]}. ${rest[1][0]}. ${rest[2]}`;
}

Any other cases of the rest ?

about 4 years ago · Juan Pablo Isaza Relatório

0

Split the string, use array spread and rest to get the first word, and the rest of the words, and the use slice to get the middle and the last words. Combine them all to a single array, map the middle words to the required form, and then flatten and join with spaces:

const initializeNames = str => {
  const [first, ...rest] = str.split(' ')
  const middle = rest.slice(0, -1)
  const last = rest.slice(-1)
  
  return [
    first, 
    middle.map(([c]) => `${c.toUpperCase()}.`), 
    last
  ].flat().join(' ')
}

const assertEquals = (a, b) => console.log(`"${a}" & "${b}" are ${a === b ? 'equal' : 'not equal'}`) 

assertEquals(initializeNames('Jack Ryan'), 'Jack Ryan');
assertEquals(initializeNames('Lois Mary Lane'), 'Lois M. Lane');
assertEquals(initializeNames('Dimitri'), 'Dimitri', '');
assertEquals(initializeNames('Alice Betty Catherine Davis'), 'Alice B. C. Davis')

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda