Linh Nguyen
Linh Nguyen

Reputation: 3880

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 = ["why", "would", "you", "pay", "for", "a", "phone", "?"];

I'm trying to group words with the same starting character in the same seperate group of array Example output would be:

firstArray = ["why", "would"] //<- all start with w
secondArray = ["you"]
thirdArray = ["pay", "phone"]//<- all start with p
fourthArray = ["for"]
fifthArray = ["a"] 
finalArray = ["?"]//<- special character like ?, :,.. in the same group

How do i achieve this ? i miswrited this and the question look like i'm asking for codes but i'm actually asking for a solution how to solve this (logic wise)

Upvotes: 1

Views: 6279

Answers (5)

Jack Bashford
Jack Bashford

Reputation: 44087

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; }

Upvotes: 1

brk
brk

Reputation: 50291

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)
  } else if (acc.hasOwnProperty(curr.charAt(0))) {
    acc[curr.charAt(0)].push(curr)
  } else {
    acc[curr.charAt(0)] = [curr]

  }
  return acc;

}, {
  special: []
})

console.log(grouped)

Upvotes: 2

Akrion
Akrion

Reputation: 18515

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].

Upvotes: 2

neaumusic
neaumusic

Reputation: 10454

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);

Upvotes: 0

ray
ray

Reputation: 27245

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 result
  return result;
}, {})

console.log(binned);

Upvotes: 6

Related Questions