【问题标题】:how to sort elements alphabetically with case sensitive如何在区分大小写的情况下按字母顺序对元素进行排序
【发布时间】:2017-01-25 09:18:24
【问题描述】:

有这个简单的功能来计算字母频率

function getFreq(str){
  var freq={};
  str.replace(/[a-z A-Z]/g, function(match){
    freq[match] = (freq[match] || 0) + 1;
    return match;
  });
  console.log(JSON.stringify(freq));
  return freq;
  
}
<input type="text" onchange="getFreq(this.value);" />

输入样本Hello World

输出:

{"H":1,"e":1,"l":3,"o":2," ":1,"W":1,"r":1,"d":1}

预期输出:

{"d":1,"e":1,"l":3,"o":2,"r":1,"H":1,"W":1," ":1}  

-----小写,然后大写,最后是空格

我尝试使用console.log(JSON.stringify(freq.sort())); 对结果进行排序,但没有成功。

【问题讨论】:

  • 对象属性没有任何顺序,但在 ES6 中它有顺序(不确定)
  • 对象实际上没有顺序。你可以拿钥匙订购它们,然后用它来展示。
  • @PranavCBalan:哦,别这么说。 :-) 他们(现在)这样做了,依赖它只是没有用。
  • 可以使用一组排序好的Object.keys来按顺序显示
  • @T.J.Crowder:更新先生,一旦你纠正我:D

标签: javascript sorting


【解决方案1】:

您的代码中没有任何东西可以对任何东西进行排序。从 ES2015 开始,对象属性将按照它们创建的顺序进行序列化(除了看起来像数组索引的东西),但这通常没有用。当您想要订购时,请使用数组。见 cmets:

// Let's use modern event handling
document.getElementById("btn").addEventListener("click", function() {
  getFreq(document.getElementById("field").value);
}, false);

function getFreq(str){
  var freq={};
  str.replace(/[a-z A-Z]/g, function(match){
    freq[match] = (freq[match] || 0) + 1;
    return match;
  });
  // Build an array with the results in string order by splitting it
  // and then mapping letters to objects with the frequency
  var result = [];
  str.split("").forEach(function(letter) {
    if (freq.hasOwnProperty(letter)) {
      result.push({letter: letter, freq: freq[letter]});
    }
  });
  console.log(result);
}
<input type="text" value="Hello world" id="field">
<input type="button" id="btn" value="Run">

技术上,您可以使用对象生成所需的输出,因为您只使用单字母字母字符串作为键,并且从 ES2015 开始,这些将按照它们的顺序进行字符串化添加到对象。 (JSON.stringify 确实 遵循 ES2015 的属性顺序。)但它只有效,因为你忽略了数字;如果包含数字,它们将不会按您想要的顺序出现(数字将按数字顺序出现在字母之前)。

纯粹用于学术目的(需要符合 ES2015 的浏览器):

// NOT A GOOD IDEA

document.getElementById("btn").addEventListener("click", function() {
  getFreq(document.getElementById("field").value);
}, false);

function getFreq(str){
  var freq={};
  str.replace(/[a-z A-Z]/g, function(match){
    freq[match] = (freq[match] || 0) + 1;
    return match;
  });
  // Build an object with the results in string order by splitting it
  // and then adding properties to an object in order
  var result = {};
  str.split("").forEach(function(letter) {
    result[letter] = freq[letter];
  });
  console.log(JSON.stringify(result));
}
<input type="text" value="Hello world" id="field">
<input type="button" id="btn" value="Run">

但是,这又依赖于您只使用字母字符的假设。

【讨论】:

    【解决方案2】:

    您可以使用自定义排序功能将所有小写字母移到前面,将大写字母移到中间,空格移到末尾。

    function getFreq(str){
        var freq = {}, result;
        str.replace(/[a-z A-Z]/g, function (match) {
            freq[match] = (freq[match] || 0) + 1;
        });
        result = Object.keys(freq).sort(function (a, b) {
            var aa = a.toLowerCase(),
                bb = b.toLowerCase();
            return (a === ' ') - (b === ' ') || (a !== aa) - (b !== bb) || aa.localeCompare(bb);
        }).map(function (k) {
            return { letter: k, count: freq[k] };
        });
        console.log(result);
        return freq;
    }
    &lt;input type="text" onchange="getFreq(this.value);" /&gt;

    【讨论】:

      【解决方案3】:

      您可以将Object.keysreduce 结合使用来执行此操作。唯一需要注意的是空格 的 ASCII 值为 32。所以它将始终是此排序列表中的第一个字符。

      参考:http://www.theasciicode.com.ar/ascii-printable-characters/space-ascii-code-32.html

      function getFreq(str){
        var freq={};
        str.replace(/[a-z A-Z]/g, function(match){
          freq[match] = (freq[match] || 0) + 1;
          return match;
        });
        console.log(JSON.stringify(freq));
        
        return Object.keys(freq)
          .sort()
          .reduce((accumulator, k) => {
            accumulator[k] = freq[k]; 
            return accumulator;
          }, {});
        
      }
      
      console.log(getFreq("Hello World"));

      【讨论】:

      • 是的。这与我想要的完全相反。将尝试颠倒顺序。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      • 2011-08-14
      • 2012-06-25
      • 1970-01-01
      • 2012-09-20
      • 2015-04-04
      相关资源
      最近更新 更多