简体   繁体   English

使用JavaScript获取数组中的最大字符串值

[英]get max string value in array using javascript

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. 其中abcd是数字。

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? 现在,如何获得此数组中a最大值, b最大值, c最大值, d最大值?

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/ JSfiddle: http : //jsfiddle.net/UQWLe/1/

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: 因此,假设您的数组按您显示的顺序排序,并且“ 1-a1”表示“组1,数字,索引1”(“ 1-a4”表示“组1,数字,索引4”和“ 2-b1” ”表示“第2组,数字,索引1”,依此类推),并假设所有部分都可以是一个以上的数字(如“ 11-8812”,也称为“第11组,数字为88,索引为12”) );您可能会遇到类似:

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 . 您还可以为max使用数组而不是对象。 The whole procedure could be simplified if the last number is always one character. 如果最后一个数字始终是一个字符,则可以简化整个过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM