Skip to content

Instantly share code, notes, and snippets.

@ZacharyL2
Last active March 3, 2022 06:36
Show Gist options
  • Save ZacharyL2/1d4694ddbf8390070bc92fe4d448358d to your computer and use it in GitHub Desktop.
Save ZacharyL2/1d4694ddbf8390070bc92fe4d448358d to your computer and use it in GitHub Desktop.
Simulation of flat
const testArray = [1, [3, [4]], [3, [4, [5]]], [2, [3, [4, [5]]]], [2, [3, [4, [5]]]]];
function flatten(arr, depth = 1) {
if (depth <= 0) return arr;
return arr.flatMap((item) => {
if (Array.isArray(item) && item.some(Array.isArray)) {
return flatten(item, depth - 1);
}
return item;
});
}
function flatten(arr, depth = 1) {
if (depth <= 0) return arr;
return arr.reduce((previousValue, currentValue) => {
// Option 1
return previousValue.concat(
Array.isArray(currentValue) ? flatten(currentValue, depth - 1) : currentValue,
);
// Option 2
// if (Array.isArray(currentValue)) {
// return [...previousValue, ...flatten(currentValue, depth - 1)];
// }
// return [...previousValue, currentValue];
}, []);
}
function flatten(arr, depth = 1) {
if (depth <= 0) return arr;
let result = [];
for (const item of arr) {
if (Array.isArray(item)) {
// Option 1
result = result.concat(flatten(item, depth - 1));
// Option 2
// result.push(...flatten(item, depth - 1));
} else {
result.push(item);
}
}
return result;
}
function flatten(arr, depth = 1) {
while (depth > 0 && arr.some((item) => Array.isArray(item))) {
depth -= 1;
// Option 1
arr = [].concat(...arr);
// Option 2
// arr = Array.prototype.concat.call([], ...arr);
// Option 3
// arr = Array.prototype.concat.apply([], arr);
}
return arr;
}
console.log('flatten(testArray, 3): ', flatten(testArray, 3));
console.log('testArray.flat(3): ', testArray.flat(3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment