0

I want to apply a function to each of the values at all levels of the array:

arr = [[1,2,3],[1,2,3],[[1,2],[1,2]],1,2,3]

for example, multiply all the values by 3, and map it in the same format as before so I get:

arr = [[3,6,9],[3,6,9],[[3,6],[3,6]],3,6,9]

What would be the best way to go about this?

I tried to use a recursive function:

function mapall(array){
         array.map(function(obj){
                   if (Array.isArray(obj)===true) { return mapall(obj) }
                   else{ return obj*3 }
                   })
            };

but when I run it I just get undefined, so I must be doing something not quite right??

Any ideas??

Thanks

2 Answers 2

4

Everything was working, but you forgot to return from array.map. Here's a cleaner version of your code:

var arr = [[1,2,3],[1,2,3],[[1,2],[1,2]],1,2,3];
function mapAll(array){
  return array.map(function(item){
    return Array.isArray(item) ? mapAll(item) : item * 3;
  });
}
alert(JSON.stringify(mapAll(arr)));

Sign up to request clarification or add additional context in comments.

Comments

2

Version with callback function where you can do with array elements what you want (el * 2 or something else)

var arr = [[1,2,3],[1,2,3],[[1,2],[1,2]],1,2,3];

function mapAll(array, cb) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (Array.isArray(array[i])) {
            mapAll(array[i], cb);
        } else {        
            array[i] = cb(array[i]);
        }
    }
    
    return array;
};

var res = mapAll(arr, function (el) {
    return el * 3;
});

console.log(JSON.stringify(res));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.