Skip to content Skip to sidebar Skip to footer

Javascript Group Words In An Array With The Same Starting Character

i'm currently studying javascript and i have problem trying to figure out how to handle this problem: i have an array of words with special question mark like this wordsArray = [

Solution 1:

You could use Array.reduce

const wordsArray = ["why", "would", "you", "pay", "for", "a", "phone", "?"];

const binned = wordsArray.reduce((result, word) => {
  // get the first letter. (this assumes no empty words in the list)const letter = word[0];
  
  // ensure the result has an entry for this letter
  result[letter] = result[letter] || [];
  
  // add the word to the letter index
  result[letter].push(word);
  
  // return the updated resultreturn result;
}, {})

console.log(binned);

Solution 2:

You can use reduce function , but for all special characters use a single array. You can initialize the accumulator with an object with default key special. In the reduce callback function check if this accumulator have an key which is is the first letter of the current element in iteration. If that is the case then push the current value in the array of key

let wordsArray = ["why", "would", "you", "pay", "for", "a", "phone", "?","-"];
var regex = /^[a-zA-Z0-9]*$/;
let grouped = wordsArray.reduce(function(acc, curr) {
  
  let isSpecial = regex.test(curr);

  if (!isSpecial) {
    acc.special.push(curr)
  } elseif (acc.hasOwnProperty(curr.charAt(0))) {
    acc[curr.charAt(0)].push(curr)
  } else {
    acc[curr.charAt(0)] = [curr]

  }
  return acc;

}, {
  special: []
})

console.log(grouped)

Solution 3:

With ES6 this would be something like this with Array.reduce and Object.values:

let data  = ["why", "would", "you", "pay", "for", "a", "phone", "?"];

let result = data.reduce((r,c) => {
  r[c[0]] = r[c[0]] ? [...r[c[0]], c] : [c]
  return r
}, {})

console.log(Object.values(result))

The idea is to create a grouping by taking the first character of the current word c[0].

Solution 4:

Use reduce:

const arr = ["why", "would", "you", "pay", "for", "a", "phone", "?"];

const res = arr.reduce((acc, [f, ...l]) => {
  (acc[f] = acc[f] || []).push(f + l.join(""));
  return acc;
}, {});

console.log(res);
.as-console-wrapper { max-height: 100%!important; top: auto; }

Solution 5:

const wordsByLetter = arr.reduce((wordsByLetter, word) => { if (Array.isArray(wordsByLetter[word.charAt(0)])) wordsByLetter[word.charAt(0)].push(word); else wordsByLetter[word.charAt(0)] = [word]; return wordsByLetter), {}); const arraysOfWords = Object.values(wordsByLetter);

Post a Comment for "Javascript Group Words In An Array With The Same Starting Character"