数组扁平化

数组扁平化

Posted by limantang on November 21, 2019

数组扁平化

  • 递归思路

function flat(array) {
  let result = [];
  for (let i  = 0; i < array.length; i++) {
    const item = array[i];
    if (item instanceof Array) {
      console.log(result, 'result');
      result = result.concat(flat(item));
    } else {
      result.push(item);
    }
  }
  console.log(result, 'return 之前');
  return result;
}
  • toString

function flat(arr) {
  const str = arr.toString();
  console.log(str);
  return str.split(',');
}

  • reduce + 递归
function flat(arr) {
  return arr.reduce((pre, current) => {
    console.log(pre, 'pre');
    console.log(current, 'current');
    const temp = Array.isArray(current) ? flat(current) : current;
    console.log(temp, 'temp');
    return pre.concat(temp);
  }, [])
}

源码地址

blog-source-code/src/arrayFlat at master · echoheart/blog-source-code · GitHub