计算字符串中的字母和数字

时间:2019-04-13 05:03:31

标签: javascript

我写的代码只适用于字母,不适用于数字 我知道这可能有点复杂,但这是我可以做到的。 用数字生成有序数组,我不知道为什么

var orderedCount = function(text) {
  let splitted = text.split('');
  let countedLetters = splitted.reduce((AllLetters, letter) => {
    (letter in AllLetters) ? AllLetters[letter]++: AllLetters[letter] = 1;
    return AllLetters
  }, {})
  let result = Object.keys(countedLetters).map((key) => {
    return [(key), countedLetters[key]]
  })
  return result;

};
console.log(orderedCount("abracadabra")); //[['a',5], ['b',2], ['r',2], ['c',1], ['d',1]]
console.log(orderedCount("212")); //[['1',1], ['2',2]]

[['1',1],['2',2]] 

应该是

[['2',2],['1',1]]

3 个答案:

答案 0 :(得分:1)

您可以使用Object.entries将对象转换为数组,并使用sort对元素1进行排序

var orderedCount = function(text) {
  let splitted = text.split('');
  let countedLetters = splitted.reduce((AllLetters, letter) => {
    (letter in AllLetters) ? AllLetters[letter]++: AllLetters[letter] = 1;
    return AllLetters
  }, {})

  let result = Object.entries(countedLetters).sort((a, b) => {
    return b[1] - a[1];
  })

  return result
};
console.log(orderedCount("abracadabra")); 
console.log(orderedCount("212"));


更短版本:

var orderedCount = function(text) {
  return Object.entries(text.split('').reduce((c, v) => {
    c[v] = (c[v] || 0) + 1;
    return c;
  }, {})).sort((a, b) => b[1] - a[1]);

};
console.log(orderedCount("abracadabra")); 
console.log(orderedCount("212"));

答案 1 :(得分:0)

您需要按计数对result进行排序,因为默认情况下,Object中的数字键将位于ascending order

var orderedCount = function(text) {
  let splitted = text.split('');
  let countedLetters = splitted.reduce((AllLetters, letter) => {
    (letter in AllLetters) ? AllLetters[letter]++: AllLetters[letter] = 1;
    return AllLetters
  }, {})
  let result = Object.keys(countedLetters).map((key) => {
    return [(key), countedLetters[key]]
  })
  return result.sort((a,b)=>b[1] - a[1]);

};
console.log(orderedCount("abracadabra")); //[['a',5], ['b',2], ['r',2], ['c',1], ['d',1]]
console.log(orderedCount("212")); //[['1',1], ['2',2]]

答案 2 :(得分:0)

您可以直接使用https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html方法创建数组,该方法使用引用对象,该引用对象根据letter的值保留对象引用。

var orderedCount = function(text) {
  const ref = {};
  return text.split('').reduce((arr, letter) => {
    (letter in ref) ? ref[letter][1]++: arr.push(ref[letter] = [letter, 1]);
    return arr;
  }, []);
};
console.log(orderedCount("abracadabra")); //[['a',5], ['b',2], ['r',2], ['c',1], ['d',1]]
console.log(orderedCount("212")); //[['1',1], ['2',2]]

引用:Array#reduce

自es2015起,非整数键将保持插入顺序,整数键将按数字排序。