Tengo este reto, que consiste en:
Por ejemplo:
debería volver
groupIt(['hola', 'adios', 'chao', 'hemos', 'accion']) // Should return { a: [ "adios", "accion" ] c: [ "chao" ] h: [ "hola", "hemos" ] }Esta es mi respuesta, devuelve el objeto esperado, pero no pasa la prueba en la página:
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'])¿Dónde estoy fallando?
Aquí la prueba: https://www.jschallenger.com/javascript-arrays/javascript-group-array-strings-first-letter
Ejecuté su código, así como los ejemplos de prueba proporcionados por JS Challenger. Me di cuenta de que eran sensibles a mayúsculas y minúsculas. Entonces, aunque su código funciona bien, si las palabras comienzan con mayúsculas, no pasará ciertos casos. Se adjunta mi versión que pasó todos los ejemplos de prueba.
Si agrega: .toLowerCase al firstChar, creo que también pasará. Feliz codificación ;)
PD: si la imagen a continuación no funciona, avíseme, estoy aprendiendo cómo contribuir a Stack Exchange, gracias.
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']}Al sitio no le gusta .reduce , pero aquí hay una forma:
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 }, {}) }Sensible a mayúsculas y minúsculas es la razón. Introduzca un toLowerCase después de charAt(0).
Aquí está mi ejemplo:
https://stackblitz.com/edit/node-tebpdp?file=ArrayStringsFirstLetter.js