记录reduce函数的各种用法

165 阅读1分钟

1. 递归遍历树形结构

/**
 * @param {data} Array 要处理的数据
 * @param {res} Array 返回的结果
 */
function flat(data = [], res = []) {
    if (Object.prototype.toString.call(data) !== "[object Array]") return;
    return data
        .reduce((t, v) => ((res.push(v), v.children) ? flat(v.children, res) : res), [])
        .map(_ => (delete _["children"], { ..._ }));
}

2. 找出数组中出现次数最多的元素

const arr = ["a", "b", "c", "b", "c", "c"];

// 正常写法
arr.reduce((t, v) => {
    if (!t[v]) {
        t[v] = 1;
    } else {
        t[v]++;
    }
    return t;
}, {});

// 三元运算写法
arr.reduce((t, v) => {
    t[v] = !t[v] ? 1 : t[v]++;
    return t;
}, {});

// 简洁写法
arr.reduce((t, v) => {
    t[v] = ++t[v] || 1;
    return t;
}, {});

//  看不懂写法
arr.reduce((t,v) => (t[v] = ++t[v] || 1, t), {})