Answers for "get flatten array from nested array"

1

flatten nested array javascript

// using recursion, .reduce() and .concat() methods
// works with arrays of any depth

function flatten(arr)
{
	return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []);
};

const arr = [[1,2],[3,[4,[5]]]];

const flattened = flatten(arr);
console.log(flattened);

/*
	Output: [ 1, 2, 3, 4, 5 ]
*/
Posted by: Guest on May-30-2020
0

get flatten array from nested array

var result = [];
function arrayFlatter (data, result){
  if (!Array.isArray(data))
    result.push(data);
  else if (Array.isArray(data)){
    let i = 0; 
    for (i = 0; i < data.length; i++){
      arrayFlatter (data[i], result);
    }
  }
}


arrayFlatter (nestedArr, result)
Posted by: Guest on July-13-2021
0

get flatten array from nested array

recurseTheFunction = async (reqData, result) => {
    try {

        await asyncForEach(reqData, async (element, i, array) => {
            if (element && element.length) {
                await recurseTheFunction(element, result)
            } else {
                result.push(element);
            }
        })

        return (result);
    } catch (error) {
        console.log(error)
    }
}

asyncForEach = async (array, callback) => {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array)
    }
}

getFlattenArray = async (arr) => {

    const finalFlattenArray = await recurseTheFunction(arr, []);
    console.log('finalFlattenArray', finalFlattenArray)
}

getFlattenArray([1, 2, 3, [4, 5, [6, 7, [8, [9]]]], 10, [11, [12, [13]]]])
Posted by: Guest on July-13-2021

Browse Popular Code Answers by Language