当前位置:   article > 正文

【前端面试】七、算法-数组展平

【前端面试】七、算法-数组展平

目录

1.判断数组

 2.二维数组展平

3.多维数组展平


1.判断数组

  1. // 判断数组
  2. console.log([].constructor === Array);
  3. console.log( Array.isArray([]));
  4. console.log( [] instanceof Array);
  5. console.log(Object.prototype.toString.call([]) === '[object Array]');

 2.二维数组展平

  1. const flattenOnce = (arr) => {
  2. return [].concat(...arr)
  3. }
  4. const arr1 = [1, [2, 3], [4, 5, 6], [7, 8, 9, 10]];
  5. console.log('flattenOnce',flattenOnce(arr1));

3.多维数组展平

递归

  1. // 多维数组展平
  2. const arr2 = [1, [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, [12, 13, [14, 15]]]];
  3. // 递归
  4. const flatten1 = (arr) => {
  5. return arr.reduce((acc, cur) => {
  6. return acc.concat(Array.isArray(cur) ? flatten1(cur) : cur)
  7. }, [])
  8. }
  9. console.log('flatten1',flatten1(arr2));
  10. // 递归
  11. const flatten2 = (arr) => {
  12. return [].concat(...arr.map(item => Array.isArray(item) ? flatten2(item) : item))
  13. }
  14. console.log('flatten2',flatten2(arr2));

字符串

  1. function flatten3(arr) {
  2. return arr.toString().split(',').map(item => +item)
  3. }
  4. console.log('flatten3',flatten3(arr2));

循环

  1. const flatten4 = (arr) => {
  2. while(arr.some(item => Array.isArray(item))) {
  3. arr = [].concat(...arr)
  4. }
  5. return arr
  6. }
  7. console.log('flatten4',flatten4(arr2));

栈的思想

  1. const flatten5 = arr => {
  2. let stack = arr.slice()
  3. const r = []
  4. while (stack.length) {
  5. const item = stack.pop()
  6. if(Array.isArray(item)){
  7. stack = stack.concat(item) //stack.push(...item)
  8. } else {
  9. r.unshift(item)
  10. }
  11. }
  12. return r
  13. }
  14. console.log('flatten5',flatten5(arr2));

生成器 

  1. function *flatten6(arr){
  2. for (let i = 0; i < arr.length; i++) {
  3. if(Array.isArray(arr[i])) {
  4. yield *flatten3(arr[i])
  5. } else{
  6. yield arr[i]
  7. }
  8. }
  9. }
  10. console.log('flatten6', [...flatten6(arr2)]);
  11. function *flatten7(arr) {
  12. let stack = arr.slice()
  13. while (stack.length) {
  14. const item = stack.shift()
  15. if(item.constructor === Array) {
  16. stack = stack.concat(item) //stack.push(...item)
  17. } else {
  18. yield item
  19. }
  20. }
  21. }
  22. console.log('flatten7', [...flatten7(arr2)]);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/935687
推荐阅读
相关标签
  

闽ICP备14008679号