最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Javascript group words in an array with the same starting character - Stack Overflow

matteradmin3PV0评论

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)

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)

Share Improve this question edited May 13, 2019 at 4:43 Ganesh Jadhav 8027 silver badges25 bronze badges asked May 13, 2019 at 4:21 Linh NguyenLinh Nguyen 3,9204 gold badges33 silver badges77 bronze badges 4
  • 8 What have you tried so far? StackOverflow is not a code writing service, you need to show what you've tried in order for us to help you fix it. – Soviut Commented May 13, 2019 at 4:22
  • i tried using indexOf(string,"0") in a forEach loop to pare each element in array with eachOther but i don't know how to find the first character and add it to the first parameter of the infexOf function – Linh Nguyen Commented May 13, 2019 at 4:25
  • Please include your attempt at the code in your question next time. – Soviut Commented May 13, 2019 at 5:04
  • ok ,i will do it next time thank – Linh Nguyen Commented May 13, 2019 at 6:37
Add a ment  | 

5 Answers 5

Reset to default 6

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

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)

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

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

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

comment list (0)

  1. No comments so far