Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var arr1 = [1, 2, [3, 4]];
- var arr2 = flattenDeep(arr1, 1);
- function flattenDeep(arr, depthValue) {
- if (Array.prototype.flat) {
- console.log('11');
- return arr.flat(depthValue);
- } else {
- console.log('22');
- var depth = depthValue;
- depth = depth === undefined ? 1 : Math.floor(depth);
- if (depth < 1) return Array.prototype.slice.call(this);
- return (function flat(arr, depth) {
- var len = arr.length >>> 0;
- var flattened = [];
- var i = 0;
- while (i < len) {
- if (i in arr) {
- var el = arr[i];
- if (Array.isArray(el) && depth > 0)
- flattened = flattened.concat(flat(el, depth - 1));
- else flattened.push(el);
- }
- i++;
- }
- return flattened;
- })(this, depth);
- }
- }
- console.log(arr2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement