使用Javascript获取数组中类似项的最大值

时间:2023-01-06 22:57:07

I have an array like this:

我有一个像这样的数组:

["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"]

[“13rq8”,“13rq6”,“13rq4”,“13rq2”,“13dl”,“12dl”,“13rq12”,“13rq10”]

and I want to get a final array that will group similar values that changes from each other only by the last numbers of the string ("13rq8", "13rq6", "13rq4", "13rq2", "13rq12", "13rq10"), and return only the biggest values like the example below:

我希望得到一个最终数组,它将相似的值组合在一起,只能通过字符串的最后一个数字(“13rq8”,“13rq6”,“13rq4”,“13rq2”,“13rq12”,“13rq10”)相互改变),并返回最大值,如下例所示:

["13dl", "12dl", "13rq12"]

[“13dl”,“12dl”,“13rq12”]

Can you help me please resolve this in Javascript?

你能帮我解决一下吗?

Thank You!

1 个解决方案

#1


0  

Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:

使用对象(例如tagNum)跟踪每个前缀的最大值,并使用正则表达式提取前缀和尾随值:

var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};

l.forEach(function(x) {
  var m = x.match(/^(.*?)(\d*)$/);
  var tag = m[1];
  var num = parseInt("0" + m[2]);
  if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});

var l2 = [];
for (var tag in tagNum) {
  var num = tagNum[tag];
  if (num) l2.push(tag + num);
  else l2.push(tag);
}

console.log(l2);

#1


0  

Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:

使用对象(例如tagNum)跟踪每个前缀的最大值,并使用正则表达式提取前缀和尾随值:

var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};

l.forEach(function(x) {
  var m = x.match(/^(.*?)(\d*)$/);
  var tag = m[1];
  var num = parseInt("0" + m[2]);
  if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});

var l2 = [];
for (var tag in tagNum) {
  var num = tagNum[tag];
  if (num) l2.push(tag + num);
  else l2.push(tag);
}

console.log(l2);