Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Javascript combine multidimensional array

How to flatten nested array in Javascript

In Javascript, we can flatten a multidimensional array recursively in a different method. Listing the most efficient solutions to flatten the nested array into a single array.

  1. We can use the array flat() method
  2. We can use the array reduce() method
  3. We can use the array map() method

Solution 1:
The best solution is we can use the flat() method to flatten nested array in Javascript. And when a flat method is been used it is necessary to pass the Infinity as the argument.

// an multi dimentional array
var array = ['name', 'email', ['phone', ['address']], 'department', ['it']];

// Sol 1 : flat with infinity
console.log(array.flat(Infinity));
// output
// ["name", "email", "phone", "address", "department", "it"]

Solution 2:
Use the reduce function to flatten the multidimensional array. Reduce method checks whether the current item is value or array. If the current item is value it will be concatenated otherwise flatByReduce method will be called recursively.

// an multi dimentional array
var array = ['name', 'email', ['phone', ['address']], 'department', ['it']];
// Sol 2: use reduce
const flatByReduce = (param) => {
    return param.reduce(function(result, nextItem) {
        return result.concat(Array.isArray(nextItem) ? flatByReduce(nextItem) : nextItem);
    }, []);
}
console.log(flatByReduce(array));
// output
// ["name", "email", "phone", "address", "department", "it"]

Solution 3:
We can also use the map method to flatten nested array in Javascript into a single array. Map method checks whether the current item is value or array. If the current item is value it will be returned otherwise flatten method will be called recursively

// an multi dimentional array
var array = ['name', 'email', ['phone', ['address']], 'department', ['it']];
// Sol 3: use map
const  flatten = (param) => {
    return [].concat(...param)
}


const flatByMap = (param) => {
    return flatten(
        param.map(item =>
            Array.isArray(item) ? flatByMap(item) : item
        )
    );
}
console.log(flatByMap(array));
// output
// ["name", "email", "phone", "address", "department", "it"]

Also read, Count occurrences of each character in a string