reduce javascript高級な使い方をまとめてみましょう.

1541 ワード

//基本的な使い方
let arr = [1, 2, 3, 4]
let sum = arr.reduce((init, item, i, k) => {
    console.log(init, "inits") 
    //init        ,       ,      。
    // console.log(item) //        
    // console.log(i,"here") //   
    // console.log(k,"k") //    
    return init + item
})
console.log(sum)
//配列のデバッグ
let arrs = [11, 11, 2, 3, 3]
let newArr = arrs.reduce((prev, cur, index, arr) => {
    prev.indexOf(cur) === -1 && prev.push(cur);
    return prev;
}, []);
//フラットな二次元配列
let arrs1 = [
    [1, 2, 8],
    [3, 4, 9],
    [5, 6, 10]
];
let res = arrs1.reduce((x, y) => x.concat(y), []);
//多次元配列フラット
function steamroller3(arr) {
    return arr.reduce((prev, next) => {
        return prev.concat(Array.isArray(next) ? steamroller3(next) : next)
    }, [])
}
//compose関数が簡潔なバージョンを実現する
function func1(a) {
    console.log(a, "hewew")
    return a * 10;
}

function func2(b) {
    console.log(b, "bbbbb")
    return b * 2
}

function func3(c) {
    return c / 2;
}
const compose = (...func) => (...init) => 
 func.reduce(
    (prev, curr, index) => curr(prev),
    ...init
);
        


const a1 = compose(func1, func2)(2);
console.log(a1) //40
const a2 = compose(func1, func2, func3)(2);
console.log(a2) //20

***                           。                 task            ***
//配列の最大値
let max = arr.reduce( (prev, cur) =>Math.max(prev,cur))