3

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

Sourabh Somani
  • 2,138
  • 1
  • 13
  • 27

3 Answers3

3

You could take a callback which checks the value and map the array or the multiplicated value.

This proposal uses Array#map and returns a new array.

var times2 = v => Array.isArray(v) ? v.map(times2) : 2 * v,
    x = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]],
    x2 = x.map(times2);

console.log(x2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

You're looking for

function nestedArrayOperation(arr, callback) {
 return arr.map(function(item,index) {
  if (Array.isArray(item))
   return nestedArrayOperation(item, callback);
        else
            return callback(item, index);
    });
}
var example = [1,2,[3,4,[5,6,[7,8,[9,10]]]]];
console.log(nestedArrayOperation(example, x=>x*2));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1
  1. Pass the callback function as parameter of prototype function.
  2. Then pass also with recursive function call
  3. For more simple form use ternary operator within Array#map

Array.prototype.nestedArrayOperation = function(callback) {
  return this.map((item, index) => Array.isArray(item) ? item.nestedArrayOperation(callback): callback(item));
}

var x = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]

console.log(x.nestedArrayOperation((x) => x + 2))
console.log(x.nestedArrayOperation((x) => x * 2))
.as-console-row-code {
  white-space: nowrap!important;
}
prasanth
  • 22,145
  • 4
  • 29
  • 53