Skip to content

Commit 8695764

Browse files
committed
Added fallback
1 parent 599113d commit 8695764

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/utils/array.js

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,34 @@ export function flatten (array) {
472472
// if not an array, return as is
473473
return array
474474
}
475-
return array.flat(Infinity)
475+
if (typeof Array.prototype.flat === 'function') {
476+
return array.flat(Infinity)
477+
} else {
478+
// TODO: once Array.prototype.flat is supported in all browsers, remove this and the _flatten function
479+
return _flatten(array)
480+
}
481+
482+
function _flatten (array) {
483+
const flat = []
484+
485+
function flattenHelper (value) {
486+
if (Array.isArray(value)) {
487+
const len = value.length
488+
for (let i = 0; i < len; i++) {
489+
flattenHelper(value[i]) // traverse through sub-arrays recursively
490+
}
491+
} else {
492+
flat.push(value)
493+
}
494+
}
495+
496+
const len = array.length
497+
for (let i = 0; i < len; i++) {
498+
flattenHelper(array[i])
499+
}
500+
501+
return flat
502+
}
476503
}
477504

478505
/**

0 commit comments

Comments
 (0)