Skip to content

数组扁平化

多维数组=>一维数组

js
let arr = [1, [2, [3, [4, 5]]], 6];
let str = JSON.stringify(arr);

直接调用 flat 方法

js
arr_flat = arr.flat(Infinity);

JSON.stringify 之后替换

js
ary = str.replace(/(\[|\])/g, "").split(",");

JSON.stringify 之后替换,再用 parse

js
str = str.replace(/(\[|\])/g, "");
str = "[" + str + "]";
ary = JSON.parse(str);

递归处理

js
let result = [];
let fn = function (ary) {
  for (let i = 0; i < ary.length; i++) {
    let item = ary[i];
    if (Array.isArray(ary[i])) {
      fn(item);
    } else {
      result.push(item);
    }
  }
};

用 reduce 实现

js
function flatten(ary) {
  return ary.reduce((pre, cur) => {
    return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
  }, []);
}

let ary = [1, 2, [3, 4], [5, [6, 7]]];
console.log(flatten(ary));

扩展运算符

js
while (ary.some(Array.isArray)) {
  ary = [].concat(...ary);
}

对象的扁平化

js
function objectFlat(obj = {}) {
  const res = {};
  function flat(item, preKey = "") {
    Object.entries(item).forEach(([key, val]) => {
      const newkey = preKey ? `${preKey}.${key}` : key;
      if (val && typeof val === "object") {
        flat(val, newKey);
      } else {
        res[newKey] = val;
      }
    });
  }
  flat(obj);
  return res;
}

const source = { a: { b: { c: 1, d: 2 }, e: 3 }, f: { g: 2 } };
console.log(objectFlat(source));