Given an array that has numbers, and arrays of numbers, leave the single number values alone, but do the following to arrays within the array with more than one number, multiply them by the number of values in the inner array.
For example, let's use this array here:
var array1 = [2, [3, 5, 4], 4, 6, 4, [3, 3, 1, 6, 4], 5, [5, 6]];
The returned array would be = [2, [9, 15, 12], 4, 6, 4, [15, 15, 5, 30, 20], 5, [10, 12]];
The first two is a single value, not in a subarray, so we do nothing to it. The following 3, 5 and 4 are in a subarray, and there are three values in that subarray, so we multiply each number in the subarray by 3, and so on.
Tip : I used map for this.
I'll post my solution in the comments.
var arrays = [[1, 2, 3], 8,[4, 5], [6]];
ReplyDeletevar example = arrays.map(function(item){
if(item.length > 1){
var length = item.length
return item.map(function(item){
return item * length;
});
}
return item * 1;
});
example;
I accidentally used the native map function instead of the underscore map function. They are identical, just slightly different in the way they're called. For underscore, instead of coding array.map, you would write _.map(arrays, function....). With the native you type the array.map(function....)
ReplyDelete