Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React typescript – split array into alphabetical groups

I have a string array with many (100+) words, I have sorted the array in alphabetical order, but I want group or split the array into hash array hashMap<String(Alphabet), List<String>>, so I can show it in this style:

Desired Result

const stringArray = [
    "Apple",
    "animal",
    "Apart",
    "ball",
    "backpack",
    "ballers",
    "bingo",
    "cars",
    "Careful",
    "Coach"
  ]

 {stringArray && stringArray?.sort(function (a, b) {
            if (a < b) { return -1; }
            if (a > b) { return 1; }
            return 0;
          }).map(word => (
            <hr><hr />
            <p>{word}</p>
          ))}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can easily achieve the result using Map or using plain object as:

Live Demo using Map

Codesandbox Demo

Live Demo using object

Codesandbox Demo

const arr = [
  "Apple",
  "animal",
  "Apart",
  "ball",
  "backpack",
  "ballers",
  "bingo",
  "cars",
  "Careful",
  "Coach",
];
const getFilteredArr = (arr) => {
  const map = new Map();
  arr
    .sort((a, b) => a.localeCompare(b))
    .forEach((str) =>
      !map.has(str[0].toLowerCase())
        ? map.set(str[0].toLowerCase(), [str])
        : map.get(str[0].toLowerCase()).push(str)
    );
  return [...map];
};
const newArray = getFilteredArr(arr);

return (
  <>
    <div>
      {newArray.map(([key, values]) => {
        return (
          <div key={key}>
            <h1>{key}</h1>
            {values.map((str) => (
              <p key={str}>{str}</p>
            ))}
          </div>
        );
      })}
    </div>
  </>
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading