【问题标题】:Grouping array based on special character count [closed]基于特殊字符计数的分组数组[关闭]
【发布时间】:2020-04-09 09:24:08
【问题描述】:

我想编写一个程序,它接受一个字符串数组并返回一个对象,该对象根据其中非字母数字字符的数量将这些字符串分组为数组。

输入

var list= ['1','1.2','1.2.3','1.23.4','1.4','11','33.44.55.66.99','ab.cd.ed.df'];

输出

var output = {
  count4:['33.44.55.66.99'],
  count3:['ab.cd.ed.df'],
  count2:['1.2.3','1.23.4'],
  count1:['1.2','1.4'],
  count0:['1','11']
}

【问题讨论】:

  • 什么不起作用?

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

你可以试试这个方法,对你有用

var list = ['1', '1.2', '1.2.3', '1.23.4', '1.4', '11', '33.44.55.66.99', 'ab.cd.ed.df'];
var output = {}

for (let i = 0; i < list.length; i++) {

    let count = list[i].split('.').length - 1;

    if (!output[`count${count}`]) {
        output[`count${count}`] = []
    }

    output[`count${count}`].push(list[i])  

}
var ordered = {};
Object.keys(output).sort().forEach(function(key) {
  ordered[key] = output[key];
});

console.log(ordered);    

【讨论】:

  • 缺少 Count4 和 count3 订单,Narendra Chouhan
  • 我已经编辑了我的答案,请检查@SamJay,如果答案正确,请点赞
  • 当然,我会的
【解决方案2】:

你可以使用一个简单的 reduce。

const list = ['1','1.2','1.2.3','1.23.4','1.4','11','33.44.55.66.99','ab.cd.ed.df'];
const obj = list.reduce((acc, cur) => {
    const dots = cur.split('.').length - 1
    const key = `count${dots}`
    return {
        ...acc,
        [key]: [...(acc[key]||[]), cur].sort()
    }
}, {});
console.log (obj)

【讨论】:

  • 谢谢 Moritz Roessler,是否有可能得到像 count0,count1,count2,count3,count4 ...等这样的序列顺序数组。
  • 用于分组其工作正常但缺少 Count4 和 count3 顺序。我需要像 count1 ,count2,count3 和 count4(asc) 或 count4 ,count3 ,count2 和 count(desc) 这样的 oder
  • @SamJay 只需在数组后添加.sort()。我更新了答案
  • 我看到你的输出,sort() 不起作用。
猜你喜欢
  • 2015-02-07
  • 2020-10-26
  • 2014-07-31
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 2021-04-06
相关资源
最近更新 更多