Home > Enterprise >  how can i count letters in a table
how can i count letters in a table

Time:11-26

Im trying to count letters and display it in a table. right now the table works but there too many rows and the count is incorrect.

A 2
B 3
C 1

how can i make the output look like this?

import {
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow
} from "@material-ui/core";
import "./styles.css";

const letters = ["A", "A", "B", "B", "B", "C"];

const Row = (letter: string) => (
  <TableRow>
    <TableCell>{letter}</TableCell>
    <TableCell>{letters.lastIndexOf(letter)}</TableCell>
  </TableRow>
);

export default function App() {
  return (
    <div className="App">
      <TableContainer component={Paper}>
        <Table sx={{ minWidth: 650 }} aria-label="simple table">
          <TableHead>
            <TableRow>
              <TableCell>letter</TableCell>
              <TableCell>count</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>{letters.map(Row)}</TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}

CodePudding user response:

lastIndexOf returns the index position of the last occurrence of the element, hence the count is off. I suggest you find the frequency of each letter before mapping.

A potential way of doing so is as follows (taken from this question):

const letters = ["A", "A", "B", "B", "B", "C"];
const counts = {};

for (const letter of letters ) {
  counts[letter ] = counts[letter ] ? counts[letter ]   1 : 1;
}

So now you can have access to the counts of each letter by doing:

<TableCell>{counts[letter]}</TableCell>

Also, there are too many rows because you are mapping over the original letters array and as such there will be one row for each occurrence of letter.

Assuming you create an object for the occurrences, you can map over that using:

Object.keys(counts).map
  • Related