数组中具有相同起始字符的Javascript组词 [英] Javascript group words in an array with the same starting character

查看:74
本文介绍了数组中具有相同起始字符的Javascript组词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习javascript,我在尝试弄清楚如何处理此问题时遇到了问题:

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,?];

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

我该如何实现?
i写错了这个,问题看起来像我在问代码,但实际上我在问一个解决方案(逻辑上)

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)

推荐答案

您可以使用 reduce 函数,但对于所有特殊字符,请使用单个数组。您可以使用默认键为 special 的对象初始化累加器。在reduce回调函数中,检查此累加器是否具有键,该键是迭代中当前元素的第一个字母。如果是这种情况,则将当前值推入 key

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)

这篇关于数组中具有相同起始字符的Javascript组词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆