2017-06-01 66 views
1

我试图映射具有n维子数组的数组。我看过深度地图,但我没有使用任何对象。什么我想要做的一个例子是:在deepMap数组在javascript中嵌套数组中映射非对象值

deepMap([4,5,[3,4,[2]]], (x) => x+5) 
    returns [9,10,[8,9,[7]]] 

的功能后,可以是任何功能

 const deepMap=(arr, fn) =>{ 
      const stop = arr.length===0; 
      const tail = arr.slice(1); 
      const head = arr[0]; 
      const front = head instanceof Array ? [head[0]]: [] ; 
      const next = fn(front, head); 
      return stop ? [] : front.concat(deepMap(tail,fn)); 

     } 

如何申请一个函数嵌套数组值,同时保持整个数组是嵌套数组?

任何帮助,非常感谢!

回答

0

使用简单的递归。对于嵌套数组,映射遍历数组递归调用deepMap。当你到达叶子时,调用该函数。

function deepMap(arr, fn) { 
 
    return arr instanceof Array ? arr.map(el => deepMap(el, fn)) : fn(arr); 
 
} 
 
console.log(deepMap([4, 5, [3, 4, [2]]], (x) => x + 5));

+0

感谢Barmar!我试图不使用if语句,但是非常棒,帮助我可视化过程。我结束了这个: 'const deepMap =(arr,fn)=> const head = arr instanceof Array? arr.map((el)=> deepMap(el,fn)):fn(arr); 回头; (deepMap([4,5,[3,4,[2]]],(x)=> x + 5));'并且它正常工作 – Timmehlkk

+0

您可以使用三元组代替: '返回arr instanceof数组? ...:...' – Barmar

0

你可能会做如在Haskellesque方式如下:

function deepMap([x,...xs],f){ 
 
    return x ? [Array.isArray(x) ? deepMap(x,f) : f(x), ...deepMap(xs,f)] 
 
      : []; 
 
} 
 
    
 

 
var arr = [4,5,[3,4,[2]]], 
 
    res = deepMap(arr, x => x+5); 
 
console.log(res);