I have an nested array like as follows
var x=[1,2,[3,4,[5,6,[7,8,[9,10]]]]]
I want to perform some operation in array suppose multiplication of each elements with 2 then the result will be as follows
[2,4,[6,8,[10,12,[14,16,[18,20]]]]]
So far I have done as follows
function nestedArrayOperation(arr){
var p=[];
arr.forEach(function(item,index){
if(Array.isArray(item)){
p.push(nestedArrayOperation(item))
return
}
p.push(item*2);//multiply by 2
return
});
return p;
}
function nestedArrayOperation(arr){
var p=[];
arr.forEach(function(item,index){
if(Array.isArray(item)){
p.push(nestedArrayOperation(item))
return
}
p.push(item*2);//Multiply by 2
return
});
return p;
}
var x=[1,2,[3,4,[5,6,[7,8,[9,10]]]]]
console.log(nestedArrayOperation(x))
.as-console-row-code{white-space: nowrap!important;}
Here I am performing operation inside the function that is hard coded, I want to make Generic nestedArrayOperation where operation will be decided by user like map, reduce etc. function works.
Like in map
function we can do any operation
[1,2,3,4].map(x=>x**2)//it will return [1,4,9,16]
or
[1,2,3,4].map(x=>x*2)//it will return [2,4,6,8]
Example like as follows:
arr.nestedArrayOperation(x=>x*2)
//or
arr.nestedArrayOperation(x=>x+5)
Please help to create that generic
Thank You