js处理数据?

想把以下数据处理成以title字段三个为一组,并合并成一个数组,如果title不是字母那就单独为一组,

const data = [  {    "title": "A",    "type": "0",    "items": [        {            "code": "092200",            "value": "阿坝"        },        {            "code": "310600",            "value": "阿克苏"        },        {            "code": "310900",            "value": "阿拉尔"        },        {            "code": "281500",            "value": "阿拉善盟"        },    ],

效果如下
image.png

阅读 1.5k
1 个回答
// 根据示意图做了个数据,关键是 title,所以其他数据省略了
const data = [
    { title: "热门城市" },
    ...[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map(ch => ({ title: ch }))
];

function chunkSpecially(list, length = 3) {
    const groups = list.reduce((g, it) => {
        const isLetter = /^[A-Z]$/i.test(it.title);
        // g.cnt 用于对字母计数,当它为 0 的时候,需要新加一组
        // 另外,如果当前不是字母,也需要新加一组
        // unshfit 是为了方便用 g[0] 取最后一组(后面要记得 reverse)
        if (!g.cnt || !isLetter) { g.unshift([]); }
        // 把当前轮询到的元素加到当前组(最后一组)
        g[0].push(it);
        // 如果满了 length,或者不是字母,cnt 置 0,准备新开组
        g.cnt = isLetter ? (g.cnt + 1) % length : 0;
        return g;
    }, (g => (g.cnt = 0, g))([]));  // ← IIFE 初始化 cnt 为 0,方便里面数学计算

    // 删除辅助属性
    delete groups.cnt;

    // 返回前记得反向数组
    return groups.reverse();
}

console.log(chunkSpecially(data));

先是想用一个 reduce 写完,所以写了个辅助属性。后来改成函数了,辅助属性可以直接改为 local variable,不需要挂在 groups 上了。

下面是改成两种情况的代码

function chunkSpecially(list, length = 3) {
    let cnt = 0;
    const groups = list.reduce((g, it) => {
        const isLetter = /^[A-Z]$/i.test(it.title);
        if (!cnt || !isLetter) { g.unshift([]); }
        g[0].push(it);
        cnt = isLetter ? (cnt + 1) % length : 0;
        return g;
    }, []);
    return groups.reverse();
}

或者直接 reduce 一句话

const groups = data
    .reduce(
        (g, it) => {
            const isLetter = /^[A-Z]$/i.test(it.title);
            if (!g.cnt || !isLetter) { g.unshift([]); }
            g[0].push(it);
            g.cnt = isLetter ? (g.cnt + 1) % 3 : 0;
            return g;
        },
        (g => (g.cnt = 0, g))([])
    )
    .reverse(); // 会带着 cnt,但是一般不影响
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题