数组扁平化

113 阅读1分钟
let arr = [[1, 2, 3], [4, 4, 5], [6, 7, 8, [9, 10, [11, 12]]], ];

// 1、ES6 flat处理
arr = arr.flat(Infinity);

// 2、通过toString()转化为字符串
arr = arr.toString().split(',').map(item => parseFloat(item));

// 3、循环验证是否为数组
while (arr.some(item => Array.isArray(item))) {
  arr = [].concat(...arr);
};
function wrap() {
  let ret = [];
  return function flat(arr) {
    for (let item of arr) {
      if (item.constructor === Array) {
        ret.concat(flat(item));
      } else {
        ret.push(item);
      }
    }
    return ret;
  }
}
function wrap(arr) {
  let ret = [];
  ret = Array.from(new Set(arr.flat(Infinity)));

  return ret;
}

// 随机生成一个长度为 10 的整数类型的数组,例如 [2, 10, 3, 4, 5, 11, 10, 11, 20],将其排列成一个新数组,要求新数组形式如下,例如 [[2, 3, 4, 5], [10, 11], [20]]。
function formArray(arr) {
  const sortedArr = Array.from(new Set(arr)).sort((a, b) => a - b);
  const map = new Map();
  debugger;
  sortedArr.forEach((v) => {
    const key = Math.floor(v / 10);
    const group = map.get(key) || [];
    group.push(v);
    map.set(key, group);
  });
  return [...map.values()];
}

// 旋转数组
function rotate(arr, k) {
  const len = arr.length;
  const step = k % len;
  return arr.slice(-step).concat(arr.slice(0, len - step));
}

// 移动0
function zeroMove(array) {
  let len = array.length;
  let j = 0;
  for (let i = 0; i < len - j; i++) {
    if (array[i] === 0) {
      array.push(0);
      array.splice(i, 1);
      i--;
      j++;
    }
  }
  return array;
}

function currying(fn, length) {
  length = length || fn.length;
  return function(...args) {
    return args.length >= length ? fn.apply(this, args) : currying(fn.bind(this, ...args), length - args.length);
  }
}

function fun(num) {
  let num1 = num / 10;
  let num2 = num % 10;
  if (num1 < 1) {
    return num;
  } else {
    num1 = Math.floor(num1);
    return`${num2}${fun(num1)}`;
  }
}