1

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?

Alex Hadley
2,1252 gold badges28 silver badges50 bronze badges
asked May 10, 2012 at 9:21
4
  • 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 ? Commented May 10, 2012 at 9:33
  • @RoyiNamir i think he wants a = 6, b = 3, c = 7, d = 7 Commented 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 elements Commented May 10, 2012 at 9:52
  • @Omran thats the result you want jsfiddle.net/UQWLe/1 ? Commented May 10, 2012 at 10:01

2 Answers 2

1

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/

answered May 10, 2012 at 9:34

Comments

0

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.

answered May 10, 2012 at 9:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.