如何获取字符串中重复的字母

How to get the repeated letter in a string?

本文关键字:字符串 何获取 获取      更新时间:2023-09-26

var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh";

在这里,我想得到输入的最大值和最小值。例如,我输入了10次字母"a"。这是最大值。所以我想低估这个价值。如何使用jquery或javascript获取字符串中输入的最大值。

具有Array#forEach()和对象count:的提案

var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh",
    count = {}, min, max;
a.split('').forEach(function (a) {
    count[a] = (count[a] || 0) + 1;
});
Object.keys(count).forEach(function (a, i) {
    if (!i) {
        min = [a];
        max = [a];
        return;
    }
    if (count[a] < count[min[0]]) {
        min = [a];
        return;
    }
    if (count[a] > count[max[0]]) {
        max = [a];
        return;
    }
    if (count[min[0]] === count[a]) {
        min.push(a);
    }
    if (count[max[0]] === count[a]) {
        max.push(a);
    }
});
document.write('min: ' + min.join(', ') + ' with occurrence of ' + count[min[0]] + '<br>');
document.write('max: ' + max.join(', ') + ' with occurrence of ' + count[max[0]] + '<br>');
document.write('<pre>' + JSON.stringify(count, 0, 4) + '</pre>');

如何使用jquery或javascript。

试试这个

var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh";
var allchars = a.split("").sort();
var output = {}; 
allchars.forEach(function(val){ output[val] = output[val] || 0; output[val]++; });

现在找到值最高的密钥

var highestProp = "";
var highestValue = 0;
var lowestProp = "";
var lowestValue = Number.MAX_SAFE_INTEGER;        
Object.keys(output).forEach(function(key){
   if (output[key] > highestValue )
   {
      highestValue = output[key];
      highestProp = key;
   }
   if (output[key] < lowestValue )
   {
      lowestValue  = output[key];
      lowestProp  = key;
   }
}); 

现在highestValuehighestProp具有最高值和最高值的属性名称。类似地,lowestValuelowestProp具有最低值和最低值属性名称。

演示

var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh";
var allchars = a.split("").sort();
var output = {}; 
allchars.forEach(function(val){ output[val] = output[val] || 0; output[val]++; });
var highestProp = "";
var highestValue = 0;
var lowestProp = "";
var lowestValue = Number.MAX_SAFE_INTEGER;
Object.keys(output).forEach(function(key){
   if (output[key] > highestValue )
   {
      highestValue = output[key];
      highestProp = key;
   }
   if (output[key] < lowestValue )
   {
      lowestValue  = output[key];
      lowestProp  = key;
   }
}); 
alert(highestProp + " has the highest frequency of " + highestValue);
alert(lowestProp + " has the lowest frequency of " + lowestValue);