Issue
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:
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>
))}
Solution
You can easily achieve the result using Map
or using plain object as:
Live Demo using Map
Live Demo using object
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>
</>
);
Answered By - decpk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.