根据特殊字符计数对数组进行分组

Grouping array based on special character count

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

输入

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']
}

您可以使用简单的 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)

你可以试试这个方法,它会为你工作

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