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?
-
1'1-61,1-62,1-63,1-64,2-31,2-32,2-33,2-34,3-71,3-72,3-73,4-71,4-72' what result will you want in this sample ?Royi Namir– Royi Namir2012年05月10日 09:33:12 +00:00Commented May 10, 2012 at 9:33
-
@RoyiNamir i think he wants a = 6, b = 3, c = 7, d = 7user1150525– user11505252012年05月10日 09:40:31 +00:00Commented May 10, 2012 at 9:40
-
no the result should be a = 64, b = 34, c = 73 and d = 72 also the it is not a string, it is an array contains string elementsOmran– Omran2012年05月10日 09:52:30 +00:00Commented May 10, 2012 at 9:52
-
@Omran thats the result you want jsfiddle.net/UQWLe/1 ?user1150525– user11505252012年05月10日 10:01:06 +00:00Commented May 10, 2012 at 10:01
2 Answers 2
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/
Comments
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.