Reputation: 559
I have an array that contains string with the following format:
1-a1,1-a2,1-a3,1-a4,2-b1,2-b2,2-b3,2-b4,3-c1,3-c2,3-c3,4-d1,4-d2
where a
, b
, c
, and d
are numbers.
Now, how can I get the max value of a
, max value of b
, max value of c
, max value of d
in this array?
Upvotes: 1
Views: 5940
Reputation: 25332
So, assuming your array is ordered as you shown, and "1-a1" means "group 1, number, index 1" (and "1-a4" means "group 1, number, "index 4" and "2-b1" means "group 2, number, index 1" and so on); and assuming that all the parts could be more than one number (like "11-8812" aka "group 11, a number like 88 and an index like 12"); you could have something like:
var array = ["1-81","1-102","1-93","1-24","2-881","2-122","2-13","2-984","3-2121","3-12","3-93","4-41","4-22"]
var max = {};
var group = "", count = 0;
for (var i = 0; i < array.length; i++) {
var parts = array[i].split("-");
if (group !== parts[0]) {
group = parts[0];
count = 0;
}
count++;
var number = +parts[1].replace(new RegExp(count + "$"), "");
max[group] = Math.max(max[group] || 0, number)
}
console.log(max)
You can also use an array instead of an object for max
. The whole procedure could be simplified if the last number is always one character.
Upvotes: 0
Reputation:
I don't know this much about regex, but try this:
var numbers = [0, 0, 0, 0]; //a = 0, b = 1, c = 2, d = 3
string.replace(/(\d)-(\d+)(,|$)/g, function($0, $1, $2) { numbers[parseInt($1) - 1] = Math.max(parseInt($2), numbers[parseInt($1) - 1]); });
Edit: I didn't know it was an array and what the result should be... . So here is my solution to your problem:
var numbers = [0, 0, 0, 0], i, j;
for(i=0,j=array.length;i<j;++i) {
array[i] = array[i].split('-');
numbers[parseInt(array[i][0]) - 1] = Math.max(numbers[parseInt(array[i][0]) - 1], parseInt(array[i][1]));
}
JSfiddle: http://jsfiddle.net/UQWLe/1/
Upvotes: 1