Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opration in Nested Array

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

like image 640
Sourabh Somani Avatar asked Feb 07 '26 01:02

Sourabh Somani


2 Answers

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));
like image 183
Bergi Avatar answered Feb 09 '26 13:02

Bergi


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; }
like image 42
Nina Scholz Avatar answered Feb 09 '26 15:02

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!