const prefixes = ['Inscribed', 'Autographed', 'Exalted', 'Corrupted'];
const prefixExpression = new RegExp(`^(${prefixes.join('|')})`, 'gi');
const items = [
{ name: 'Corrupted Demon Eater', price: '3215.00', inStock: 1 },
{ name: 'Exalted Demon Eater', price: '1530.00', inStock: 1 },
{ name: 'Demon Eater', price: '2900.00', inStock: 1 },
{ name: 'Whalehook', price: '1000.00', inStock: 1 },
{ name: 'Whalehook', price: '590.00', inStock: 1 },
{ name: 'Whalehook', price: '259.20', inStock: 1 },
{ name: 'Whalehook', price: '259.15', inStock: 1 },
{ name: 'Autographed Whalehook', price: '243.00', inStock: 1 },
{ name: 'Autographed Whalehook', price: '344.00', inStock: 1 },
{ name: 'Autographed Whalehook', price: '199.00', inStock: 1 },
{ name: 'Inscribed Whalehook', price: '355.00', inStock: 1 },
{ name: 'Inscribed Whalehook', price: '655.00', inStock: 1 },
{ name: 'Inscribed Whalehook', price: '5555.00', inStock: 1 },
{ name: 'Inscribed Sylvan Cascade', price: '345.00', inStock: 1 },
{ name: 'Inscribed Sylvan Cascade', price: '96.18', inStock: 1 },
{ name: 'Inscribed Sylvan Cascade', price: '95.00', inStock: 1 },
{ name: 'Inscribed Sylvan Cascade', price: '266.71', inStock: 1 },
{ name: 'Inscribed Sylvan Cascade', price: '85.00', inStock: 1 }
];
const getCheapest = items => {
const store = items.reduce((accumulator, item) => {
const type = item.name.replace(prefixExpression, '').trim();
if (!accumulator.has(type)) {
accumulator.set(type, []);
}
accumulator.get(type).push(item);
return accumulator;
}, new Map());
const cheapest = store.values().reduce((accumulator, items) => {
const minPrice = Math.min(...items.map(item => parseFloat(item.price)));
const item = items.find(item => parseFloat(item.price) === minPrice);
accumulator.push(item);
return accumulator;
}, []);
return cheapest;
};
getCheapest(items);
/*
[
{ name: 'Exalted Demon Eater', price: '1530.00', inStock: 1 },
{ name: 'Autographed Whalehook', price: '199.00', inStock: 1 },
{ name: 'Inscribed Sylvan Cascade', price: '85.00', inStock: 1 }
]
*/