[英]How to count the number of each consecutive unique character of a string in javascript
How to count the number of each consecutive unique character of a string.如何计算字符串中每个连续唯一字符的数量。
Case exampe:
// Function Name : CountUniqueChar()
// Input : String
// Output : Array Object [{k: v}]
// Example :
// Input : “aaaasssiia”
// output : [{“a”: 4}, {“s”: 3}, {“i”: 2}, {“a”: 1}]
Using matchAll()
with a regular expression and map()
:将
matchAll()
与正则表达式和map()
:
const count = (s) => [...s.matchAll(/(.)\\1*/g)].map(([{length}, c]) => ({[c]: length})); console.log(count('aaaasssiia'));
Use for loop
to iterate over each character in a string and compare with next character to keep count of consecutive unique char.使用
for loop
遍历字符串中的每个字符并与下一个字符进行比较以保持连续唯一字符的计数。
const input = "aaaasssiia"; const countChar = (str) => { const list = []; let count = 1; for (let i = 0; i < str.length; i++) { if (str[i] === str[i + 1]) { count++ } else { const obj = {}; obj[str[i]] = count; list.push(obj); count = 1; } } return list; } console.log(countChar(input))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.