Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Group array of strings by first letter

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']}
 Run code snippet
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Group #array #strings #letter
ADD COMMENT
Topic
Name
6+6 =