慕码人2483693
您只在中返回一个数组reduce()。您还需要返回第二个。在第一次迭代中,ais [[],[]]。但是在第一个之后,它将仅成为单个阵列。let A = [1,2,3,4]const res= A.reduce((a,v,i)=> v % 2 == 0 ? [a[0],[...a[1],v]] : [[...a[0],v],a[1]],[[],[]])console.log(res)您可以在此处使用技巧。由于v % 2将返回1或者0所以你可以push()到和使用,返回原来的a不扩散运营商。let A = [1,2,3,4]const res= A.reduce((a,v,i)=> (a[v % 2].push(v),a),[[],[]])console.log(res)
慕田峪7331174
您可以使用解构分配来简化此操作-const data = [ 1, 2, 3, 4 ]const result = data.reduce ( ([ odd, even ], v) => Boolean (v & 1) ? [ [...odd, v], even ] : [ odd, [...even, v] ] , [ [], [] ] ) console.log(result)// [ [ 1, 3 ], [ 2, 4 ] ]您可以创建一个通用函数,partition-const partition = (p, a = []) => a.reduce ( ([ t, f ], v) => p (v) ? [ [...t, v], f ] : [ t, [...f, v] ] , [ [], [] ] )const evenOdds = partition (v => Boolean (v & 1), [ 1, 2, 3, 4 ])const lessThan2 = partition (v => v < 2, [ 1, 2, 3, 4 ]) console.log(evenOdds)// [ [ 1, 3 ], [ 2, 4 ] ]console.log(lessThan2)// [ [ 1 ], [ 2, 3, 4 ] ]