How can we highlight the most repeated character like the 5 most frequent characters in the text. Here is the code that is used to count each character from the textarea.
import React, { useState, useMemo } from "react";
const removeSpace = (text) => text.replace(/\s/g, "");
function Home() {
const [text, setText] = useState("");
const eachCharResult = useMemo(() => {
let result = {};
let textWithoutSpace = removeSpace(text);
for (let i = 0; i < textWithoutSpace.length; i ) {
if (result[textWithoutSpace[i]]) result[textWithoutSpace[i]] ;
else result[textWithoutSpace[i]] = 1;
}
return result;
}, [text]);
return (
<div>
<form>
<h3>Please enter text</h3>
<textarea
onChange={(e) => setText(e.target.value)}
placeholder="start typing"
></textarea>
<p>Total number of character :{removeSpace(text).length}</p>
</form>
{Object.keys(eachCharResult).map((el, i) => (
<p key={i}>{`${el}: ${eachCharResult[el]}`}</p>
))}
</div>
);
}
export default Home;
I want to highlight the text that are repeated most frequently in the text like in image t
is repeated for 5
times followed by s e o i
. Displaying them as most repeated character
and show total count of t s e o i
CodePudding user response:
From what I can tell you are aiming for, you want to list the 5 most common characters and their counts. You can sort an array of entries, keep the top 5 results, and then map them to JSX.
Object.entries(eachCharResult)
.sort(([, a], [, b]) => b - a) // <-- sort by the values (i.e. letter counts)
.slice(0, 5) // <-- keep first 5 entries
.map(([key, value], i) => (
<p key={key}>
{key}: {value}
</p>
))