Home > Software design >  React typescript - split array into alphabetical groups
React typescript - split array into alphabetical groups

Time:12-12

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>
          ))}

CodePudding user response:

You can easily achieve the result using 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>
  </>
);

CodePudding user response:

You don't need a custom sort function, JS sorts alphabetically by default. So first sort your words:

words.sort();

Then iterate over them and add them to a 2nd map that is keyed off of the starting letter:

const letterMap = new Map();
words.forEach(word => {
  const letter = word[0].toUpperCase();
  if (!letterMap.has(letter)) letterMap.set(letter, []);
  letterMap.get(letter).push(word);
});

Now letterMap looks like: {'A': ['Apple', 'Animal', ...], 'B': [...]}, and you can iterate over this using letterMap.entries:

const HTML = [...letterMap.entries()].forEach((letter, words) => {
  return `${letter}<hr><hr />`  
         `<p>${words.join(' ')}</p>`;
})
  • Related