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?
-
You should be able to find the length of the longest array by extending the Array type. See stackoverflow.com/questions/1669190/….Rob Lyndon– Rob Lyndon2013年06月24日 06:01:48 +00:00Commented Jun 24, 2013 at 6:01
2 Answers 2
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;
});
8 Comments
Array#map needs a polyfill for IEwhile(len--) instead of the classic for loop? It's not actually faster.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 readablewhile(i.length < max) to do the padding. The top notch in readability IMO.As you said, your task is split into two:
- Find the maximum array length
- 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
apply.