Javascript Function Not Flattening Array Properly

时间:2017-12-18 05:17:25

标签: javascript arrays nested

I put together a JavaScript function that is supposed to flatten a nested array. However, this method always just returns the original array. For example, running this function with the following array [1, 2, 3, [4, 5, [6], [ ] ] ] will just return that array. I know there are ways to do this with reduce, but what logical reason is preventing this method from working? .map should allow me to manipulate a return value and return that within the new array through the recursion call.

function mapper(array) { 
    return array.map((item) => {
        return (Array.isArray(item)) ? mapper(item) : item
    } 
)}

2 个答案:

答案 0 :(得分:0)

You are mapping the array to itself. Basically because map will return an array with exact same number of elements as the input. You cant expect it to return more, so you cant use it for flattening the array.

Should use reduce instead:

 function flatten(obj) {

     if (Array.isArray(obj)) {
          return obj.reduce((a, b) => a.concat(flatten(b)), []);
     } else {
          return [obj];
     }
 }

答案 1 :(得分:0)

what logical reason is preventing this method from working?

 var m = [1, 2, 3, [4, 5, [6], []]];
 function mapper(array) { 
        return array.map((item) => {
            // for 1,2,3 it will return item
            // when it sees an array it will again call mapper & map
            // function will return a new array from it, so map on 
            // [4, 5, [6], []] will return a new array but will not take out
            // individual element and will put it in previous array

            return (Array.isArray(item)) ? mapper(item) : item
        } 
    )}
mapper(m)

map function does not mutate the original array but it will return a new array.