1

I have an array something like this

a=[
[1,6,6,8,0], 

[7,3,2,6],


[7,3,2]

] 

Here, I need to find the maximum length of the inside array. And I need to replace other with '0'.

For example the first array has 5 elements, which is the maximum length, so I need to put '0' to the 2nd and 3rd array till reaches the maximum lengh (i.e 5). What should I do here?

1

2 Answers 2

5
var max = Math.max.apply(null, a.map(function(i) {
    return i.length;
}));
var new_arr = a.map(function(i) {
    var pad = max - i.length;
    while (pad--) {
        i.push(0);
    } 
    return i;
});

http://jsfiddle.net/Mgfnf/1/

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

8 Comments

Note: Array#map needs a polyfill for IE
Any reason to use while(len--) instead of the classic for loop? It's not actually faster.
@Jan Dvorak: for for we would require to have another variable (because no one would use i.length in for loop exit condition). So it's just - personal choice that I think is a bit more readable
Not really. Unless you're fighting for miliseconds and want to cache the length, of course.
I would use while(i.length < max) to do the padding. The top notch in readability IMO.
|
2

As you said, your task is split into two:

  1. Find the maximum array length
  2. Pad the arrays to meet that length

Both #1 and #2 can be achieved through a simple loop through the outer array. In the first, we keep a variable (let's call it maxLength) which will hold, yes, our max length.

var maxLength = 0;
//walk through the array
for (var i = 0; i < a.length; i += 1) {
    //choose the larger
    maxLength = Math.max(maxLength, a[i].length);
}

Now that we have the size we wish to expand to, we go over the outer loop, and on each sub-array, we push 0s until the lengths match:

//walk through the array
for (var j = 0; j < a.length; j += 1) {
    //the length will increase by 1 on each push
    while (a[j].length < maxLength) {
        a[j].push(0);
    }
}

And that's it.

2 Comments

Downvoter, could you please explain? Did I make a mistake somewhere?
I see no reason for a downvote. In fact, I think this answer might be the most useful for OP. OP should first make sure he knows how to tackle this kind of problem with simple code before even learning the fancy solutions using apply.

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.