reduce用法

165 阅读2分钟
// 求和
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i);
// 指定初始值   5+30
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i, 5 );
// 与上面一样  5+30
[3, 5, 4, 3, 6, 2, 3, 4].reduce(function(a, i){return (a + i)}, 0 );
// 乘法
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a * i);


// 查找数组中的最大值:
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => Math.max(a, i), -Infinity);
// 如果你确实想在数组中找到最大值,那就不要使用上面的方法,你可以这样:
Math.max(...[3, 5, 4, 3, 6, 2, 3, 4]);

// 连接不均匀的数组
let data = [    ["The","red", "horse"],
    ["Plane","over","the","ocean"],
    ["Chocolate","ice","cream","is","awesome"], 
    ["this","is","a","long","sentence"]
  ]
  let dataConcat = data.map(item=>item.reduce((a,i)=>`${a} ${i}`))
  
  // Result
  ['The red horse',   'Plane over the ocean',   'Chocolate ice cream is awesome',   'this is a long sentence']

//   删除数组中的重复项:
let dupes = [1,2,3,'a','a','f',3,4,2,'d','d']
let withOutDupes = dupes.reduce((noDupes, curVal) => {
  if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) }
  return noDupes
}, [])
// 上面这种删除数组中重复项的,最好是用set


// 按属性分组
let obj = [    {name: 'Alice', job: 'Data Analyst', country: 'AU'},    {name: 'Bob', job: 'Pilot', country: 'US'},    {name: 'Lewis', job: 'Pilot', country: 'US'},    {name: 'Karen', job: 'Software Eng', country: 'CA'},    {name: 'Jona', job: 'Painter', country: 'CA'},    {name: 'Jeremy', job: 'Artist', country: 'SP'},  ]
let ppl = obj.reduce((pre,curr)=>{
    let newpre = curr['country']
    if(!pre[newpre]){
        pre[newpre]=[]   //新建一个对象,每个对象中以country为名字
    }
    pre[newpre].push(curr)
    return pre
},{})

// [AU: Array(1), US: Array(2), CA: Array(2), SP: Array(1)]
// AU: [{…}]
// CA: (2) [{…}, {…}]
// SP: [{…}]
// US: (2) [{…}, {…}]


// 展开一个嵌套数组
let flattened = [[3, 4, 5], [2, 5, 3], [4, 5, 6]].reduce(
    (singleArr, nextArray) => singleArr.concat(nextArray), [])
  // results is [3, 4, 5, 2, 5, 3, 4, 5, 6]
// 上面这种是递归的写法,也可以用.flat实现同样的事情
[ [3, 4, 5],
  [2, 5, 3],
  [4, 5, 6]
].flat();

// 只计算正数的幂
[-3, 4, 7, 2, 4].reduce((acc, cur) => {
    if (cur> 0) {
      let R = cur**2;
      acc.push(R);
    }
    return acc;
  }, []);
  
  // Result
  [16, 49, 4, 144]
//   就好像同时实现了映射和过滤器一样。


// 反转字符串
const reverseStr = str=>[...str].reduce((a,v)=>v+a)
// 这不仅适用于字符串,也适用于任何对象,要注意,通过这种语法,
// 我们在函数中有了reduce,因此我们可以调用reverseStr("Hola"),并且它会给出aloH。