Published
Edited
Nov 17, 2021
Insert cell
# Flatten Array
Insert cell
arr = [0, 1, 2, [3, 4, [5, 6], 7], 8, [9, 10], 11]
Insert cell
// 递归
flat = function flat(arr) {
return Array.isArray(arr) ? [].concat(...arr.map(flat)) : arr;
}
Insert cell
flat3 = function flat(arr) {
return arr.reduce((a, b) => a.concat(Array.isArray(b) ? flat(b) : b), []);
}
Insert cell
flat5 = function flat(arr) {
const res = [];
const dfs = (ar) => {
if (Array.isArray(ar)) ar.forEach(dfs);
else res.push(ar);
};
dfs(arr);
return res;
}
Insert cell
// 非递归
flat2 = (arr) => {
const res = [],
st = arr.slice().reverse();
while (st.length) {
const item = st.pop();
if (Array.isArray(item)) {
st.push(...item.slice().reverse());
} else res.push(item);
}
return res;
}
Insert cell
flat4 = function flat(arr) {
while (arr.some(Array.isArray)) {
arr = [].concat(...arr);
}
return arr;
}
Insert cell
flat(arr)
Insert cell
flat2(arr)
Insert cell
flat3(arr)
Insert cell
flat4(arr)
Insert cell
flat5(arr)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more