# Flattening each array in the array

Flattening each array in the array
0

#1

So I need to flatten each array in the array in order

" given a nested array or arrays, return a new, flat array with all the elements of all the nested arrays in their original order"

so I was gonna use for each to push each flattened array to a new array

``````
function flattenArray (arrayOfArrays) {
var originalArray = arrayOfArrays
// using this to save the unmodified array cos flattened messes with it
var flattenedArray = []
//creating place to store result of flattening each array in array
arrayOfArrays.forEach(flatten)
// creating flattened array by calling it on array of arrays
arrayOfArrays = originalArray
//making sure original arrayofarrays is unmodified

function flatten (arrayItem)
{
flattenedArray.push (arrayItem.flat())
}
//function to flatten array
return flattenedArray;

}

``````

however it wont accept .flat() for some reason
here’s the result I get when trying to run it

#2

Ok I dont think you can use flat() on an array so this should work instead

``````function flattenArray (arrayOfArrays) {
var arr1 = []

arrayOfArrays.forEach(flatten)
return arr1

function flatten (x)
{
for(i=0;i<x.length;i++)
arr1.push(x[i])
}
console.log(arr1)
// given a nested array or arrays, return a new, flat array with all the elements of all the nested arrays in their original order
}

``````

#3

2 things are wrong here

Like I said in the other answer, assignment does not create a new copy of an array. All it does is create a reference to the original array. You need to use an immutable method to create a new array

``````flattenedArray.push (arrayItem.flat())
``````

There is no `flat()` method in javascript. And here you are trying to call the `flat()` method on the passed in item.

Add this line and you’ll see what I mean

`````` function flatten (arrayItem)
{
const methods = Object.getOwnPropertyNames(arrayItem).filter(
p => typeof arrayItem[p] === "function");
console.log({ arrayItem, methods, typeOf: typeof arrayItem });
flattenedArray.push (arrayItem.flat())
}
//function to flatten array
return flattenedArray;

}
``````

#4

beat me to it. Is your code still failing?

#5

nah it works now thanks though Ill leave the thread though for other people who have a similar mixup