Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Test
- const test = require('ava');
- const reduce = require('./reduce');
- test('Can groupBy', (t) => {
- const input = [
- {
- "type": "hotel",
- "name": "Intercontinental"
- },
- {
- "type": "airport",
- "name": "Heathrow"
- },
- {
- "type": "hotel",
- "name": "Hilton"
- },
- {
- "type": "station",
- "name": "King's Cross"
- },
- {
- "type": "airport",
- "name": "Stansted"
- }
- ];
- const expected = {
- airport: ['Heathrow', 'Stansted'],
- station: "King's Cross",
- hotel: ['Intercontinental', 'Hilton']
- }
- const reduced = reduce(input);
- t.deepEqual(expected, reduced);
- });
- // Solution
- const reduce = (input) => {
- const result = input.reduce((collection, element) => {
- const current = collection[element.type]
- if(current && Array.isArray(current)) {
- collection[element.type].push(element.name);
- } else if(current) {
- collection[element.type] = [current, element.name]
- } else {
- collection[element.type] = element.name
- }
- return collection;
- }, {})
- return result;
- };
- module.exports = reduce;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement