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

184
Visualizações
Group array of strings by first letter

I have this challenge, which consists on:

  • Writing a function that takes an array of strings as argument
  • Then, group the strings in the array by their first letter
  • Return an object that contains properties with keys representing first letters

For example:

Should return

groupIt(['hola', 'adios', 'chao', 'hemos', 'accion'])

// Should return
{ 
 a: [ "adios", "accion" ]
 c: [ "chao" ]
 h: [ "hola", "hemos" ]
​}

This is my answer, it returns the expected object, but doesn't pass the test in the page:

function groupIt(arr) {
  let groups = {}
  
  let firstChar = arr.map(el=>el[0])
  let firstCharFilter = firstChar.filter((el,id)=>{
    return firstChar.indexOf(el)===id
  })
 
  firstCharFilter.forEach(el=>{
    groups[el]=[]
  })
  
  firstCharFilter.forEach(char=>{
    for(let word of arr) {
      if(word[0]==char) {
        groups[char].push(word)
      }
    }
  })
    
  return groups
}

groupIt(['hola', 'adios', 'chao', 'hemos', 'accion'])

Where am I failing at?

Here the test: https://www.jschallenger.com/javascript-arrays/javascript-group-array-strings-first-letter

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I ran your code as well as the test examples provided by JS challenger. I noticed that they where case sensitive. So although your code works well, if the words begin with upper case it will not pass certain cases. Attached is my version that passed all test examples.

If you add : .toLowerCase to the firstChar, I believe you will pass as well. Happy coding ;)

P.S if the image below does not work please let me know, I am just learning how to contribute to Stack Exchange, thanks.

const groupIt = (array) => {
  let resultObj = {};
  
  for (let i =0; i < array.length; i++) {
    let currentWord = array[i];
    let firstChar = currentWord[0].toLowerCase();
    let innerArr = [];
    if (resultObj[firstChar] === undefined) {
       innerArr.push(currentWord);
      resultObj[firstChar] = innerArr
    }else {
      resultObj[firstChar].push(currentWord)
    }
  }
  return resultObj
}

console.log(groupIt(['hola', 'adios', 'chao', 'hemos', 'accion']))

console.log(groupIt(['Alf', 'Alice', 'Ben'])) // { a: ['Alf', 'Alice'], b: ['Ben']}

console.log(groupIt(['Ant', 'Bear', 'Bird'])) // { a: ['Ant'], b: ['Bear', 'Bird']}
console.log(groupIt(['Berlin', 'Paris', 'Prague'])) // { b: ['Berlin'], p: ['Paris', 'Prague']}

about 4 years ago · Juan Pablo Isaza Relatório

0

The site doesn't like .reduce, but here's one way:

const r1 = groupIt(['hola', 'adios', 'chao', 'hemos', 'accion'])
console.log(r1)

// Should return
// {
//   a: ["adios", "accion"]
//   c: ["chao"]
//   h: ["hola", "hemos"]
// }

function groupIt(arr) {
  return arr.reduce((store, word) => {
    const letter = word.charAt(0)
    const keyStore = (
      store[letter] ||     // Does it exist in the object?
      (store[letter] = []) // If not, create it as an empty array
    ); 
    keyStore.push(word)

    return store
  }, {})
}

about 4 years ago · Juan Pablo Isaza Relatório

0

Case sensitive is the reason. Pop a toLowerCase in after the charAt(0).

Here's my example:

https://stackblitz.com/edit/node-tebpdp?file=ArrayStringsFirstLetter.js

Link to screenshot!

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