JavaScript - How to Map a list of names to a specified key using reduce
You don't need the alphabet array, you can just reduce based on the first letter:
names.reduce((obj, {name}) => {
const firstLetter = name[0];
if (firstLetter in obj) {
obj[firstLetter].push(name);
} else {
obj[firstLetter] = [name];
}
return obj;
}, {});
You can get the first character and use it as a key in the object accumulator of Array#reduce
.
If the key is present add the word starting with the key in the corresponding array:
const alphabets = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
const names = [{ name: 'Apple' },{ name: 'Apricot' },{ name: 'Avocados' },{ name: 'Almond' },
{ name: 'Blueberries' }, { name: 'Bing Cherry' },{ name: 'Breadfruit' },{ name: 'Bananas' },
{ name: 'Cherries' },{ name: 'Custard-Apple' },{ name: 'Carrot' },{ name: 'Cranberries' },
{ name: 'Dates' }, { name: 'Dragon Fruit' },{ name: 'Durian' },
{ name: 'Grapefruit' },{ name: 'Grapes' },{ name: 'Gooseberries' },{ name: 'Guava' }];
const grouped = names.reduce((r, {name}) => {
const key = name && name[0].toUpperCase();
r[key] = r[key] || [];
r[key].push(name);
return r;
}, {});
console.log(grouped);
You can just use first letter of name to be a key of value.
const groupedNames = names.reduce((acc, item) => {
const firstLetter = item.name.charAt(0);
if (!acc[firstLetter]) {
acc[firstLetter] = [item.name];
return acc;
};
acc[firstLetter].push(item.name);
return acc;
}, {})
You could take a logical nullish assignment ??=
operator fro assigning an array to a cetrain property and push the actual destrctured name.
const
names = [{ name: 'Apple' }, { name: 'Apricot' }, { name: 'Avocados' }, { name: 'Almond' }, { name: 'Blueberries' }, { name: 'Bing Cherry' }, { name: 'Breadfruit' }, { name: 'Bananas' }, { name: 'Cherries' }, { name: 'Custard-Apple' }, { name: 'Carrot' }, { name: 'Cranberries' }, { name: 'Dates' }, { name: 'Dragon Fruit' }, { name: 'Durian' }, { name: 'Grapefruit' }, { name: 'Grapes' }, { name: 'Gooseberries' }, { name: 'Guava' }],
grouped = names.reduce(
(r, { name }) => ((r[name[0].toUpperCase()] ??= []).push(name), r),
{}
);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }