使用reduce求和、将js对象转化为树形结构

文章目录

  • 1 使用reduce求和
  • 2 将js对象转化为树形结构

1 使用reduce求和

  • arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],求和
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function add(arr) {
    let sum = arr.reduce((total, item) => total + item, 0);
    return sum;
}
console.log(add(arr)); //55
  • arr = [1, 2, 3, [[4, 5], 6], 7, 8, 9],求和
arr = [1, 2, 3, [[4, 5], 6], 7, 8, 9];

function add(arr) {
    let sum = arr.flat(Infinity).reduce((total, item) => total + item, 0);
    return sum;
}
console.log(add(arr)); //45
  • arr = [{ a: 1, b: 3 }, { a: 2, b: 3, c: 4 }, { a: 3 }],求和
arr = [{ a: 1, b: 3 }, { a: 2, b: 3, c: 4 }, { a: 3 }];

function add(arr) {
    let sum = arr.reduce((total, item) => total + item['a'], 0);
    return sum;
}
console.log(add(arr)); //6

2 将js对象转化为树形结构

//转换前:
source = [{
    id: 1,
    pid: 0,
    name: 'body'
}, {
    id: 2,
    pid: 1,
    name: 'title'
}, {
    id: 3,
    pid: 2,
    name: 'div'
}];
//转换后:
tree = [{
    id: 1,
    pid: 0,
    name: 'body',
    children: [{
        id: 2,
        pid: 1,
        name: 'title',
        children: [{
            id: 3,
            pid: 1,
            name: 'div'
        }]
    }]
}];
function jsonToTree(data) {
    let result = [];
    if (!Array.isArray(data)) return result;
    let map = {};
    data.forEach(item => {
        map[item.id] = item;
    });
    data.forEach(item => {
        let parent = map[item.pid];
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            result.push(item);
        }
    });
    return result;
}

你可能感兴趣的:(前端面试,javascript,前端,开发语言)