Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

多维数组扁平化的6种方法 #56

Open
z0nka1 opened this issue Feb 14, 2021 · 0 comments
Open

多维数组扁平化的6种方法 #56

z0nka1 opened this issue Feb 14, 2021 · 0 comments

Comments

@z0nka1
Copy link
Owner

z0nka1 commented Feb 14, 2021

方法一:使用 toString()

思路:使用toString()函数后,数组会变成英文逗号分隔的字符串,再使用split()转为数组。

function flat(arr) {
  return arr.toString().split(',');
}

const array = [1, 2, [3, 4, [5, 6]]];
const flatted = flat(array);
console.log(flatted); // [1, 2, 3, 4, 5, 6]

方法二:使用递归

思路:遍历数组每一项,如果当前项不是数组,则把它放到结果数组里面,如果是数组,则再执行上述逻辑。

function flat(arr) {
  let result = [];
  for (const item of arr) {
    if (Array.isArray(item)) {
      result = result.concat(flat(item, result));
    } else {
      result.push(item);
    }
  }
  return result;
}

const array = [1, 2, [3, 4, [5, 6]]];

const flatted = flat(array);

console.log(flatted); // [1, 2, 3, 4, 5, 6]

方法三:使用正则

思路:使用JSON.stringify()将数组转为字符串,然后去掉“[”和“]”,再转为数组。

function flat(arr) {
  const str = JSON.stringify(arr);

  const flattedStr = str.replace(/\[|\]/g, '');

  return JSON.parse(`[${flattedStr}]`);
}

const array = [1, 2, [3, 4, [5, 6]]];

const flatted = flat(array);

console.log(flatted); // [1, 2, 3, 4, 5, 6]

方法四:使用 reduce()

思路:混合使用reduce()和递归,将每一项展开后拼接起来。

function flat(arr) {
   return arr.reduce((acc, current) => {
      return acc.concat(Array.isArray(current) ? flat(current) : current);
   }, [])
}

const array = [1, 2, [3, 4, [5, 6]]];
console.log(flat(array)); // [1, 2, 3, 4, 5, 6]

**注意:**这里一定要给reduce()一个空数组的默认值,否则有可能会报错。如果不给默认值,第一次迭代时acc就是数组的第一项,如果数组第一项是非数组,那么acc.concat()就会报错。

方法五:使用扩展运算符

思路:判断传入的数组,只要存在数组的项是数组,就用...运算符展开,每次循环会展开一层,直至完全展开。

function flat(arr) {
  while (arr.some(item => Array.isArray(item))) {
    arr = [].concat(...arr);
  }
  return arr;
}

const array = [1, 2, [3, 4, [5, 6]]];
console.log(flat(array)); // [1, 2, 3, 4, 5, 6]

更直观地分解以上过程:

const a = [1, 2, [3, 4, [5, 6]]];
const b = [].concat(...a); // [1, 2, 3, 4, [5, 6]]
const c = [].concat(...b); // [1, 2, 3, 4, 5, 6]

方法六:使用ES6 flat() 函数

const array = [1, 2, [3, 4, [5, 6]]];
const flatted = array.flat(Infinity);

console.log(flatted); // [1, 2, 3, 4, 5, 6]

flat() 的参数传入数组的嵌套层数,如果嵌套层数未知,可以考虑使用Infinity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant