By manipulating the mentioned codes, i framed a code as such -
Proceed() {
// some basic interfaces to describe types
interface Item {
item_text: string;
}
interface LetterRange {
first: string;
last: string;
}
// the letter ranges
// this solution allows them to intersect
// can adjust for any letter ranges
const rangesAtoH: LetterRange[] = [
{first: 'a', last: 'h'},
];
const rangesItoQ: LetterRange[] = [
{first: 'i', last: 'q'},
];
const rangesRtoZ: LetterRange[] = [
{first: 'r', last: 'z'}
];
const dropdownParameter: Item[] = [
{ item_text: 'Organisation' },
{ item_text: 'EwayBill' },
{ item_text: 'SAP' },
{ item_text: 'Collection' },
{ item_text: 'Cancel' },
{ item_text: 'Generate' },
{ item_text: 'Payments' },
{ item_text: 'SMS' },
{ item_text: 'Update' }
];
// sort the words alphabetically so that they will appear in the right order
const sorted: Item[] = this.dropdownParameter.sort((a,b) => a.item_text.localeCompare(b.item_text));
console.log("inside Proceed, Sorted = ", sorted)
// -------------------------- Array 2 - suggestion-----------------------------
// array of grouped items (each group is array as well)
const grouped: Item[][] = sorted.reduce((groups, item) => {
const firstLetter: string = item.item_text.slice(0,1).toLowerCase();
console.log(firstLetter);
// run through each range and check whether the 'firstLetter' fits there
rangesAtoH.forEach((range, index) => {
if (firstLetter >= range.first.toLowerCase()
&& firstLetter <= range.last.toLowerCase()) {
groups[index].push(item);
}
});
return groups;
}, new Array(rangesAtoH.length).fill([])); // initialise with N empty arrays
console.log("grouped", grouped);
// ---letter range I to Q ------------------
const groupedItoQ: Item[][] = sorted.reduce((groups, item) => {
const firstLetter: string = item.item_text.slice(0,1).toLowerCase();
console.log(firstLetter);
// run through each range and check whether the 'firstLetter' fits there
rangesItoQ.forEach((range, index) => {
if (firstLetter >= range.first.toLowerCase()
&& firstLetter <= range.last.toLowerCase()) {
groups[index].push(item);
}
});
return groups;
}, new Array(rangesItoQ.length).fill([])); // initialise with N empty arrays
console.log("grouped I to Q = ", groupedItoQ);
// ---letter range R to Z ------------------
const groupedRtoZ: Item[][] = sorted.reduce((groups, item) => {
const firstLetter: string = item.item_text.slice(0,1).toLowerCase();
console.log(firstLetter);
// run through each range and check whether the 'firstLetter' fits there
rangesRtoZ.forEach((range, index) => {
if (firstLetter >= range.first.toLowerCase()
&& firstLetter <= range.last.toLowerCase()) {
groups[index].push(item);
}
});
return groups;
}, new Array(rangesRtoZ.length).fill([])); // initialise with N empty arrays
console.log("grouped I to Q = ", groupedRtoZ);
}