gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:38:40 24 4
gpt4 key购买 nike

我编写的代码适用于字母但不适用于数字我知道这可能有点复杂,但我就是这样做的;它用数字生成有序数组,我不知道为什么

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]]

最佳答案

可以使用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"));

关于javascript - 计算字符串中的字母和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55662199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com