Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
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 May 10 '12 at 9:33
    
@RoyiNamir i think he wants a = 6, b = 3, c = 7, d = 7 –  user1150525 May 10 '12 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 elements –  Omran May 10 '12 at 9:52
    
@Omran thats the result you want jsfiddle.net/UQWLe/1 ? –  user1150525 May 10 '12 at 10:01
add comment

2 Answers

up vote 1 down vote accepted

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/

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.