Search
 
SCRIPT & CODE EXAMPLE
 

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
Comment

PREVIOUS NEXT
Code Example
Javascript :: json stringify close circle 
Javascript :: switch case in javascript 
Javascript :: js get element by index 
Javascript :: get element innerhtml jquery 
Javascript :: google auth.onstatechange 
Javascript :: formik react native 
Javascript :: set timeout for loop 
Javascript :: sort nested data using sort function javascript 
Javascript :: jquery form serialize object 
Javascript :: find a single element in array of objects javascript 
Javascript :: how to merge 2 object array by the same key with lodash 
Javascript :: spawn template playcanvas 
Javascript :: flatten array recursively 
Javascript :: js array backwards 
Javascript :: as it does not contain a package.json file. react 
Javascript :: Disable click for specific elements javascript 
Javascript :: javascript inject html 
Javascript :: diagonal Difference in 2D arrays javascript 
Javascript :: export all javascript 
Javascript :: string concatenation javascript 
Javascript :: jq each loop 
Javascript :: execute php 
Javascript :: array.unshift in javascript 
Javascript :: javascript last child 
Javascript :: store input into array javascript 
Javascript :: js array find regex 
Javascript :: what is 5+5 
Javascript :: javascript compare values of two arrays 
Javascript :: react native webview not working 
Javascript :: get timezone name from date javascript 
ADD CONTENT
Topic
Content
Source link
Name
9+2 =