在Jquery中查找字母数字字符串数组中的最大数字

时间:2017-01-03 06:18:29

标签: javascript jquery arrays validation sorting

我有一个包含如下数据的数组

 var arr = [Daaguva1, Dagguva2, Dagguva3, Dagguva4, Daggu5, Dag6, Dagguv7, Dagg8, Daggs9, Dagguvati10];

我想获得此数组字符串中的最大数字,即10。 我需要这个号码,以便我可以自动将数字增加到11。有什么帮助吗?

5 个答案:

答案 0 :(得分:2)

使用Array#reduce方法



var arr = ['Daaguva1', 'Dagguva2', 'Dagguva3', 'Dagguva4', 'Daggu5', 'Dag6', 'Dagguv7', 'Dagg8', 'Daggs9', 'Dagguvati10'];

// iterate over the array
var num = arr.reduce(function(g, str) {
  // get the number from string and parse it
  var num = parseInt(str.match(/\d+/)[0], 10) || 0;
  // return the greater value
  return g < num ? num : g;
  // set the initial value as lowest value 
  // either negative infinity or 0 as your requirement
}, -Infinity);

console.log(num);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

function getMaxValuefromArray() {
     var maxNum = parseInt(arr[0].replace( /^\D+/g, ''), 10),
         tempNum;

     for(var i=0; i<arr.length; i++){
          tempNum = parseInt(arr[i].replace( /^\D+/g, ''), 10);
          if (tempNum > maxNum) {
                   maxNum = tempNum;
          }
     }
     return maxNum;

}

小提琴https://jsfiddle.net/881juLr9/

答案 2 :(得分:1)

如果所有名称都匹配相同的结构(字母后跟目标号码) - 然后使用正则表达式去除所有非数字字符,并使用parseInt剩余部分产生一个数字。设置一个高分并迭代数组并将精简数字与高值进行比较,如果它更高 - 将最高值设置为该值。

&#13;
&#13;
  var arr = ['Daaguva1', 'Dagguva2', 'Dagguva3', 'Dagguva4', 'Daggu5', 'Dag6', 'Dagguv7', 'Dagg8', 'Daggs9', 'Dagguvati10'];
  
  var high=0;
  for(i=0; i<arr.length; i++){
    var num = parseInt(arr[i].replace(/\D+/g, ''));
    if(num > high){high = num};
    } 
  console.log('highest number is: ' + high);
  
  var nextNum = high +=1;
  console.log('next number will be: '+ nextNum )
&#13;
&#13;
&#13;

答案 3 :(得分:1)

var regEx = /\d+/;
var arr = ["Daaguva1", "Dagguva2", "Dagguva3", "Dagguva4", "Daggu5", "Dag6", "Dagguv7", "Dagg8", "Dagguvati10"];

var bigestIndex=0;
arr.map(function(data){
	var numIndex=data.match(regEx).index;
	if(numIndex>bigestIndex)
	bigestIndex=numIndex;
});

console.log('bigestIndex',bigestIndex);

答案 4 :(得分:0)

很简单。

var arr = ['Daaguva1', 'Dagguva2', 'Dagguva3', 'Dagguva4', 'Daggu5', 'Dag6', 'Dagguv7', 'Dagg8', 'Daggs9', 'Dagguvati10'];
var r = /\d+/; // this is regex to detect digits
var max = 0;
for(var i= 0 ; i<arr.length;i++){ // iterate over the array
    if(max < parseInt(arr[i].match(r)[0])){ // match it and if larger number found then assign it to `max`
        max = arr[i].match(r)[0];
    }
}
console.log(max);

JsFiddle