4th argument in reduce - javascript

Here is the function:
function chunk(array: number[], size: number): number[][] {
return array.reduce((chunks, curr, _, arr) => {
console.log(arr.length); // -> 10 which is correct
// let len = arr.length; // -> Cannot read properties of undefined (reading 'length')
let len = chunks.length; // this works
if (len === 0 || chunks[len - 1].length === size) chunks.push([curr]);
else chunks[len - 1].push(curr);
return chunks;
}, []);
}
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)); // ->[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]
The fourth argument to reduce is the array that we're iterating over. I can log it and I get the correct result (10) see above. But when I try to use it and assign it to a variable I get an error(see above). Could someone please shed some light?

From Mozilla's page, the fourth parameter is the array that is being reduced. You should access the array variable that is already declared, but the fourth parameter works.
For example:
array.reduce((_, __, ___, arr) => {
console.log(arr.length == array.length) // true, this is the source array
});
The reason why you're getting the error is not because of the arr.length property, but rather the way you're accessing chunks.

Related

Skipping comparison arrays when they are empty

I have a case that has to compare some arrays together and find the common element between all of them. The following code is working fine as long as all the array are loaded. But what if one (or even 5 of arrays) of the array is/are still empty and not loaded?
In case of having only two arrays I could do something like
if ((arr1.length > 0) && (arr2.length === 0)) {
newArr =arr1;
}
but it is going be a big conditional snippet to check all 6 arrays in this way! How can I fix this so the code runs comparison against arrays only when they are loaded and skip the array(s) when they are empty?
let newArr = [];
function common(arr1, arr2, arr3, arr4,arr5,arr6) {
newArr = arr1.filter(function(e) {
return arr2.indexOf(e) > -1 &&
arr3.indexOf(e) > -1 &&
arr4.indexOf(e) > -1 &&
arr4.indexOf(e) > -1 &&
arr5.indexOf(e) > -1 &&
arr6.indexOf(e) > -1;
});
}
common( [1, 2, 6, 5, 9,8],
[1, 2, 3, 6, 5, 9,8],
[6, 5, 4, 5,8],
[8, 2, 1, 6, 4],
[8, 2, 1, 6, 4],
//[8]
[]
);
$('div').text(newArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> Returns Nothing Because 6th Array is Empty</p>
<div></div>
You are doing it very hard way. Below is a very simple way.You do it in following steps:
Use Rest Parameters instead of arr1,arr2,....
Remove the empty arrays using filter(). Like Array.filter(x => x.length)
Create a object which will contain keys as number. And value as their count.
Use forEach() on array of arrays.
Increment the count of the object by apply forEach() on each of array.
At last filter those keys of object which have count greater than given object.
function common(...arrays) {
let obj = {};
let temp = arrays.filter(x => x.length);
//the below line will check if all the arrays empty
if(!temp.length) console.log("All empty")
temp.forEach(arr => {
arr.forEach(x => {
obj[x] = obj[x] + 1 || 1
})
})
//console.log(temp)
//console.log(Object.keys(obj))
return Object.keys(obj).filter(a => obj[a] === temp.length).map(x => +x || x);
}
let newArr = common( [1, 2, 6, 5, 9,8],
[1, 2, 3, 6, 5, 9,8],
[6, 5, 4, 5,8,1],
[8, 2, 1, 6, 4],
[8, 2, 1, 6, 4],
//[8]
);
console.log(newArr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
Since your code is written in ES6, there is a very ES6-way to go about your problem.
What you basically want is to check all items in the first array against n number of arrays provided in the function's parameters/arguments and only return the item that is present in all arrays.
// Use ...arrs to store all subsequent arrays in parameter
function common(arr1, ...arrs) {
return arr1.map(item => {
const nonEmptyArrs = arrs.filter(arr => arr.length);
// Go through all OTHER arrays and see if your item is present in them
const isItemFound = nonEmptyArrs.forEach(arr => {
return arr.indexOf(item) > -1;
});
// Now filter the array to remove all `false` entries
const itemFoundCount = isItemFound.filter(i => i).length;
// Only return item if it is found in ALL arrays
// i.e. itemFoundCount must match the number of arrays
if (itemFoundCount === nonEmptyArrs.length) {
return item;
}
})
.filter(item => item); // Remove undefined entries
}
See proof-of-concept below:
function common(arr1, ...arrs) {
return arr1.map(item => {
const nonEmptyArrs = arrs.filter(arr => arr.length);
const itemFoundCount = nonEmptyArrs
.map(arr => arr.includes(item))
.filter(i => i)
.length;
// Only return item if it is found in ALL arrays
if (itemFoundCount === nonEmptyArrs.length) {
return item;
}
}).filter(item => item);
}
const newArr = common([1, 2, 6, 5, 9, 8], [1, 2, 3, 6, 5, 9, 8], [6, 5, 4, 5, 8], [8, 2, 1, 6, 4], [8, 2, 1, 6, 4], []);
console.log(newArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Problem with Mocha test when try to use the 'return' in the function

I am learning the Mocha test for js but have a weird problem an couldn't figure it out. Any big man can help me:
I do this test case:
it("remove all the number larger than 10", () => {
function filter(arr) {
return arr.filter(number => number < 11);
}
assert.equal(filter([1, 3, 3, 5, 10, 29, 3], [1, 3, 3, 5, 10, 3]));
});
But it returns undefined for that filter function, but when I remove the return keyword, it works fine:
it("remove all the number larger than 10", () => {
function filter(arr) {
arr.filter(number => number < 11);
}
assert.equal(filter([1, 3, 3, 5, 10, 29, 3], [1, 3, 3, 5, 10, 3]));
});
Can anyone can explain it to me?
Thanks
You've got a typo, your close paren ) for filter should be immediately after the first array instead of after both arrays.
Also, to compare arrays use assert.deepEqual instead of assert.equal:
it("remove all the number larger than 10", () => {
function filter(arr) {
return arr.filter(number => number < 11);
}
assert.deepEqual(filter([1, 3, 3, 5, 10, 29, 3]), [1, 3, 3, 5, 10, 3]); // SUCCESS
});
(The reason why it was passing when you removed the return keyword is that filter was being passed both arrays, then returning undefined. assert.equal was only being called with one argument so its second argument was implicitly undefined. Since undefined == undefined your test passed.)

Array with unique values using array helper functions

I was playing with ES6 array helper functions reduce() and find(). I'm trying to display array of unique elements. But it is failing in case of value 0. I'm not able to find what's wrong with my code. Please guide.
Here is my code snippet:
var arrayWithDuplicates = [0, 0, 1, 2, 3, 3, 4, 4, 'a', 'a'];
var arrayWithUniqueValues = arrayWithDuplicates
.reduce((previous, item) => {
if(!previous.find(element => element === item)) {
previous.push(item)
}
return previous;
}, []);
console.log('arrayWithUniqueValues', arrayWithUniqueValues)
I'm getting below output:
arrayWithUniqueValues [ 0, 0, 1, 2, 3, 4, 'a' ]
Why I'm getting 0 twice while all other values are unique?
You can achieve the same result by converting your array into a Set and back to an Array.
var arrayWithUniqueValues = [...new Set(arrayWithDuplicates)];
The reason your code doesn't work, by the way, is that Array.prototype.find returns the element it found. When you search for 0, it returns 0 and then !0 is true. So 0 is added even if it is already in the array. You can do instead:
if (previous.indexOf(item) === - 1) {
previous.push(item);
}
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
when you got 0,the code becomes :
arrayWithDuplicates.reduce(([0], 0) => {
if(!previous.find(element => element === item)) {
//![0].find(0=>0===0),return 0,so !0 means true
previous.push(item)
//so [0,0]
}
return previous;
});
a better way is
let a=[...new Set([0, 0, 1, 2, 3, 3, 4, 4, 'a', 'a'])];//[0, 1, 2, 3, 4, "a"]

Error parsing array through IF Statement

I need to loop through an entire 2D array (OldTable) to check that Column1 has a value of 1 and Col7 is not empty (null). If the above conditions are true then push the current (i) arrays of elements into newTable.
My snippet of JS is as follow...
var newTable = [];
for (var i=1; i<OldTable.length; i++){
if(OldTable[i][0]==1 && OldTable[i][7]!==null){
newTable.push(OldTable[i]);
}
}
Seems like a fairly straight forward thing to do but currently hitting brick wall with this error...
TypeError: Cannot read property "0" from undefined. (line 80, file
"Code"
I have tried to reduce the if statement to just...
if(OldTable[i][0]==1){
...but still the same error.
I'm able to display the array element just fine using...
Browser.msgBox(OldTable[50][0]);
I'm fairly new to JS so could be a simple silly error someone could point out.
UPDATE: In trying to simplying naming, I've actually made it more difficult with conflicting terminology, so have going through and updated the variable names used.
Your code should work if, as noted in the comment by #Massimo, you change your loop from starting at i=1 to i=0, as shown below. Also, just to whet your appetite for more modern tools within JavaScript, I also include an essentially identical solution to the problem using ES6/ES2015.
var myArray = [
[1, 0, 0, 0, 0, 0, 0, 'foo' ], // should pass
[9, 1, 1, 1, 1, 1, 1, 'foo' ], // should fail
[1, 2, 2, 2, 2, 2, 2, 'foo' ], // should pass
[1, 3, 3, 3, 3, 3, 3, null ], // should fail
[0, 4, 4, 4, 4, 4, 4, null ], // should fail
[1, 5, 5, 5, 5, 5, 5, undefined], // should pass
[1, 6, 6, 6, 6, 6, 6, 'foo' ] // should pass
];
function f1(array) {
var newArray = [];
for (var i = 0; i < array.length; i++) {
if (array[i][0] == 1 && array[i][7] !== null) {
newArray.push(array[i]);
}
}
return newArray;
}
const f2 = array => array.filter(e => e[0] === 1 && e[7] !== null);
console.log(f1(myArray));
console.log(f2(myArray));

Javascript recursive array flattening

I'm exercising and trying to write a recursive array flattening function. The code goes here:
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push(flatten(arguments[i]));
}
flat.push(arguments[i]);
}
return flat;
}
The problem is that if I pass there an array or nested arrays I get the "maximum call stack size exceeded" error. What am I doing wrong?
The problem is how you are passing the processing of array, if the value is an array then you are keep calling it causing an infinite loop
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push.apply(flat, flatten.apply(this, arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat;
}
Demo: Fiddle
Here's a more modern version:
function flatten(items) {
const flat = [];
items.forEach(item => {
if (Array.isArray(item)) {
flat.push(...flatten(item));
} else {
flat.push(item);
}
});
return flat;
}
The clean way to flatten an Array in 2019 with ES6 is flat()
Short Answer:
array.flat(Infinity)
Detailed Answer:
const array = [1, 1, [2, 2], [[3, [4], 3], 2]]
// All layers
array.flat(Infinity) // [1, 1, 2, 2, 3, 4, 3, 2]
// Varying depths
array.flat() // [1, 1, 2, 2, Array(3), 2]
array.flat(2) // [1, 1, 2, 2, 3, Array(1), 3, 2]
array.flat().flat() // [1, 1, 2, 2, 3, Array(1), 3, 2]
array.flat(3) // [1, 1, 2, 2, 3, 4, 3, 2]
array.flat().flat().flat() // [1, 1, 2, 2, 3, 4, 3, 2]
Mozilla Docs
Can I Use - 95% Jul '22
If the item is array, we simply add all the remaining items to this array
function flatten(array, result) {
if (array.length === 0) {
return result
}
var head = array[0]
var rest = array.slice(1)
if (Array.isArray(head)) {
return flatten(head.concat(rest), result)
}
result.push(head)
return flatten(rest, result)
}
console.log(flatten([], []))
console.log(flatten([1], []))
console.log(flatten([1,2,3], []))
console.log(flatten([1,2,[3,4]], []))
console.log(flatten([1,2,[3,[4,5,6]]], []))
console.log(flatten([[1,2,3],[4,5,6]], []))
console.log(flatten([[1,2,3],[[4,5],6,7]], []))
console.log(flatten([[1,2,3],[[4,5],6,[7,8,9]]], []))
[...arr.toString().split(",")]
Use the toString() method of the Object. Use a spread operator (...) to make an array of string and split it by ",".
Example:
let arr =[["1","2"],[[[3]]]]; // output : ["1", "2", "3"]
A Haskellesque approach...
function flatArray([x,...xs]){
return x !== undefined ? [...Array.isArray(x) ? flatArray(x) : [x],...flatArray(xs)]
: [];
}
var na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10],
fa = flatArray(na);
console.log(fa);
So i think the above code snippet could be made easier to understand with proper indenting;
function flatArray([x,...xs]){
return x !== undefined ? [ ...Array.isArray(x) ? flatArray(x)
: [x]
, ...flatArray(xs)
]
: [];
}
var na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10],
fa = flatArray(na);
console.log(fa);
If you assume your first argument is an array, you can make this pretty simple.
function flatten(a) {
return a.reduce((flat, i) => {
if (Array.isArray(i)) {
return flat.concat(flatten(i));
}
return flat.concat(i);
}, []);
}
If you did want to flatten multiple arrays just concat them before passing.
If someone looking for flatten array of objects (e.g. tree) so here is a code:
function flatten(items) {
const flat = [];
items.forEach(item => {
flat.push(item)
if (Array.isArray(item.children) && item.children.length > 0) {
flat.push(...flatten(item.children));
delete item.children
}
delete item.children
});
return flat;
}
var test = [
{children: [
{children: [], title: '2'}
],
title: '1'},
{children: [
{children: [], title: '4'},
{children: [], title: '5'}
],
title: '3'}
]
console.log(flatten(test))
Your code is missing an else statement and the recursive call is incorrect (you pass the same array over and over instead of passing its items).
Your function could be written like this:
function flatten() {
// variable number of arguments, each argument could be:
// - array
// array items are passed to flatten function as arguments and result is appended to flat array
// - anything else
// pushed to the flat array as-is
var flat = [],
i;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat = flat.concat(flatten.apply(null, arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat;
}
// flatten([[[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]], [[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]]]);
// [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
Modern but not crossbrowser
function flatten(arr) {
return arr.flatMap(el => {
if(Array.isArray(el)) {
return flatten(el);
} else {
return el;
}
});
}
This is a Vanilla JavaScript solution to this problem
var _items = {'keyOne': 'valueOne', 'keyTwo': 'valueTwo', 'keyThree': ['valueTree', {'keyFour': ['valueFour', 'valueFive']}]};
// another example
// _items = ['valueOne', 'valueTwo', {'keyThree': ['valueTree', {'keyFour': ['valueFour', 'valueFive']}]}];
// another example
/*_items = {"data": [{
"rating": "0",
"title": "The Killing Kind",
"author": "John Connolly",
"type": "Book",
"asin": "0340771224",
"tags": "",
"review": "i still haven't had time to read this one..."
}, {
"rating": "0",
"title": "The Third Secret",
"author": "Steve Berry",
"type": "Book",
"asin": "0340899263",
"tags": "",
"review": "need to find time to read this book"
}]};*/
function flatten() {
var results = [],
arrayFlatten;
arrayFlatten = function arrayFlattenClosure(items) {
var key;
for (key in items) {
if ('object' === typeof items[key]) {
arrayFlatten(items[key]);
} else {
results.push(items[key]);
}
}
};
arrayFlatten(_items);
return results;
}
console.log(flatten());
Here's a recursive reduce implementation taken from absurdum that mimics lodash's _.concat()
It can take any number of array or non-array arguments. The arrays can be any level of depth. The resulting output will be a single array of flattened values.
export const concat = (...arrays) => {
return flatten(arrays, []);
}
function flatten(array, initial = []) {
return array.reduce((acc, curr) => {
if(Array.isArray(curr)) {
acc = flatten(curr, acc);
} else {
acc.push(curr);
}
return acc;
}, initial);
}
It can take any number of arrays or non-array values as input.
Source: I'm the author of absurdum
Here you are my functional approach:
const deepFlatten = (array => (array, start = []) => array.reduce((acc, curr) => {
return Array.isArray(curr) ? deepFlatten(curr, acc) : [...acc, curr];
}, start))();
console.log(deepFlatten([[1,2,[3, 4, [5, [6]]]],7]));
A recursive approach to flatten an array in JavaScript is as follows.
function flatten(array) {
let flatArray = [];
for (let i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
flatArray.push(...flatten(array[i]));
} else {
flatArray.push(array[i]);
}
}
return flatArray;
}
let array = [[1, 2, 3], [[4, 5], 6, [7, 8, 9]]];
console.log(flatten(array));
// Output = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
let array2 = [1, 2, [3, [4, 5, 6]]];
console.log(flatten(array2));
// Output = [ 1, 2, 3, 4, 5, 6 ]
The function below flat the array and mantains the type of every item not changing them to a string. It is usefull if you need to flat arrays that not contains only numbers like items. It flat any kind of array with free of side effect.
function flatten(arr) {
for (let i = 0; i < arr.length; i++) {
arr = arr.reduce((a, b) => a.concat(b),[])
}
return arr
}
console.log(flatten([1, 2, [3, [[4]]]]));
console.log(flatten([[], {}, ['A', [[4]]]]));
Another answer in the list of answers, flattening an array with recursion:
let arr = [1, 2, [3, 4, 5, [6, 7, [[8], 9, [10]], [11, 13]], 15], [16, [17]]];
let newArr = [];
function steamRollAnArray(list) {
for (let i = 0; i < list.length; i++) {
if (Array.isArray(list[i])) {
steamRollAnArray(list[i]);
} else {
newArr.push(list[i]);
}
}
}
steamRollAnArray(arr);
console.log(newArr);
To simplify, check whether the element at an index is an array itself and if so, pass it to the same function. If its not an array, push it to the new array.
This should work
function flatten() {
var flat = [
];
for (var i = 0; i < arguments.length; i++) {
flat = flat.concat(arguments[i]);
}
var removeIndex = [
];
for (var i = flat.length - 1; i >= 0; i--) {
if (flat[i] instanceof Array) {
flat = flat.concat(flatten(flat[i]));
removeIndex.push(i);
}
}
for (var i = 0; i < removeIndex.length; i++) {
flat.splice(removeIndex - i, 1);
}
return flat;
}
The other answers already did point to the source of the OP's code malfunction. Writing more descriptive code, the problem literally boils down to an "array-detection/-reduce/-concat-recursion" ...
(function (Array, Object) {
//"use strict";
var
array_prototype = Array.prototype,
array_prototype_slice = array_prototype.slice,
expose_internal_class = Object.prototype.toString,
isArguments = function (type) {
return !!type && (/^\[object\s+Arguments\]$/).test(expose_internal_class.call(type));
},
isArray = function (type) {
return !!type && (/^\[object\s+Array\]$/).test(expose_internal_class.call(type));
},
array_from = ((typeof Array.from == "function") && Array.from) || function (listAlike) {
return array_prototype_slice.call(listAlike);
},
array_flatten = function flatten (list) {
list = (isArguments(list) && array_from(list)) || list;
if (isArray(list)) {
list = list.reduce(function (collector, elm) {
return collector.concat(flatten(elm));
}, []);
}
return list;
}
;
array_prototype.flatten = function () {
return array_flatten(this);
};
}(Array, Object));
borrowing code from one of the other answers as proof of concept ...
console.log([
[[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]],
[[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]]
].flatten());
//[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, ..., ..., ..., 0, 1, 2]
I hope you got all kind of different. One with a combination of recursive and "for loop"/high-order function. I wanted to answer without for loop or high order function.
Check the first element of the array is an array again. If yes, do recursive till you reach the inner-most array. Then push it to the result. I hope I approached it in a pure recursive way.
function flatten(arr, result = []) {
if(!arr.length) return result;
(Array.isArray(arr[0])) ? flatten(arr[0], result): result.push(arr[0]);
return flatten(arr.slice(1),result)
}
I think the problem is the way you are using arguments.
since you said when you pass a nested array, it causes "maximum call stack size exceeded" Error.
because arguments[0] is a reference pointed to the first param you passed to the flatten function. for example:
flatten([1,[2,[3]]]) // arguments[0] will always represents `[1,[2,[3]]]`
so, you code ends up calling flatten with the same param again and again.
to solve this problem, i think it's better to use named arguments, rather than using arguments, which essentially not a "real array".
There are few ways to do this:
using the flat method and Infinity keyword:
const flattened = arr.flat(Infinity);
You can flatten any array using the methods reduce and concat like this:
function flatten(arr) { return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []); };
Read more at:
https://www.techiedelight.com/recursively-flatten-nested-array-javascript/
const nums = [1,2,[3,4,[5]]];
const chars = ['a',['b','c',['d',['e','f']]]];
const mixed = ['a',[3,6],'c',[1,5,['b',[2,'e']]]];
const flatten = (arr,res=[]) => res.concat(...arr.map((el) => (Array.isArray(el)) ? flatten(el) : el));
console.log(flatten(nums)); // [ 1, 2, 3, 4, 5 ]
console.log(flatten(chars)); // [ 'a', 'b', 'c', 'd', 'e', 'f' ]
console.log(flatten(mixed)); // [ 'a', 3, 6, 'c', 1, 5, 'b', 2, 'e' ]
Here is the breakdown:
loop over "arr" with "map"
arr.map((el) => ...)
on each iteration we'll use a ternary to check whether each "el" is an array or not
(Array.isArray(el))
if "el" is an array, then invoke "flatten" recursively and pass in "el" as its argument
flatten(el)
if "el" is not an array, then simply return "el"
: el
lastly, concatenate the outcome of the ternary with "res"
res.concat(...arr.map((el) => (Array.isArray(el)) ? flatten(el) : el));
--> the spread operator will copy all the element(s) instead of the array itself while concatenating with "res"
var nestedArr = [1, 2, 3, [4, 5, [6, 7, [8, [9]]]], 10];
let finalArray = [];
const getFlattenArray = (array) => {
array.forEach(element => {
if (Array.isArray(element)) {
getFlattenArray(element)
} else {
finalArray.push(element)
}
});
}
getFlattenArray(nestedArr);
In the finalArray you will get the flattened array
Solution using forEach
function flatten(arr) {
const flat = [];
arr.forEach((item) => {
Array.isArray(item) ? flat.push(...flatten(item)) : flat.push(item);
});
return flat;
}
Solution using reduce
function flatten(arr) {
return arr.reduce((acc, curr) => {
if (Array.isArray(curr)) {
return [...acc, ...flatten(curr)];
} else {
return [...acc, curr];
}
}, []);
}
I think you are very close. One of the problems are that you call the flatten function with the same arguments. We can make use of the spread operator (...) to make sure we are calling flatten on the array inside of arguments[i], and not repeating the same arguments.
We also need to make a few more adjustments so we're not pushing more items into our array than we should
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push(...flatten(...arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat;
}
console.log(flatten([1,2,3,[4,5,6,[7,8,9]]],[10,11,12]));
function flatArray(input) {
if (input[0] === undefined) return [];
if (Array.isArray(input[0]))
return [...flatArray(input[0]), ...flatArray(input.slice(1))];
return [input[0], ...flatArray(input.slice(1))];
}
you should add stop condition for the recursion .
as an example
if len (arguments[i]) ==0 return
I have posted my recursive version of array flattening here in stackoverflow, at this page.

Categories

Resources