最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

using reduce to flatten array in JavaScript - Stack Overflow

programmeradmin0浏览0评论

I'm getting a little confused with using reduce.

it's array.reduce((accumulator, value) => do something with accumulator, why is this returning back an empty array?

let a = [
  [1,2],
  [
    [3,4]
  ],
  [
    [[5],[6]]
  ]
];

const flatten = arr => arr.reduce((a, v) => {
  v instanceof Array ? flatten(v) : a.push(v);
  return a;
}, [])


console.log(flatten(a));

I'm getting a little confused with using reduce.

it's array.reduce((accumulator, value) => do something with accumulator, why is this returning back an empty array?

let a = [
  [1,2],
  [
    [3,4]
  ],
  [
    [[5],[6]]
  ]
];

const flatten = arr => arr.reduce((a, v) => {
  v instanceof Array ? flatten(v) : a.push(v);
  return a;
}, [])


console.log(flatten(a));

Share Improve this question asked Feb 8, 2019 at 2:41 totalnoobtotalnoob 2,74110 gold badges39 silver badges72 bronze badges 2
  • Is there a reason Array.prototype.flat() or Array.prototype.flatMap() is not being used? – guest271314 Commented Feb 8, 2019 at 2:49
  • 2 I'm learning how to use reduce. but good to know there is a native method – totalnoob Commented Feb 8, 2019 at 2:50
Add a ment  | 

3 Answers 3

Reset to default 6

The flatten(v) returns an array, but you're not doing anything with it currently. Try pushing the spread array into the accumulator instead:

let a = [
  [1,2],
  [
    [3,4]
  ],
  [
    [[5],[6]]
  ]
];

const flatten = arr => arr.reduce((a, v) => {
  v instanceof Array ? a.push(...flatten(v)) : a.push(v);
  return a;
}, [])


console.log(flatten(a));

Or, you can use concat, and only use the conditional operator when you need the entire thing to resolve to an expression (don't use it as an alternative to if/else):

let a = [
  [1,2],
  [
    [3,4]
  ],
  [
    [[5],[6]]
  ]
];

const flatten = arr => arr.reduce((a, v) => {
  if (v instanceof Array) {
    return a.concat(flatten(v))
  } else {
    a.push(v);
    return a;
  }
}, [])


console.log(flatten(a));

let arr = [[1,2],[[3,4]],[[[5],[6]]]];

const flattenArr = (arr) => 
  arr.reduce((acc, val) => 
   Array.isArray(val) ? 
    acc.concat(flattenArr(val)) :
     acc.concat(val), []);
 
console.log(flattenArr(arr));

let array = [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20, 22]]

const flatten = array.reduce((a, b) => {
  return a.concat(b)
})

console.log(flatten)

.concat concatenates two arrays, reduce does a loop under the hood and concatenation results in flattening.

发布评论

评论列表(0)

  1. 暂无评论