Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save okwolf/350aed6f74223ca5415c0cf06f6dc2f1 to your computer and use it in GitHub Desktop.
Save okwolf/350aed6f74223ca5415c0cf06f6dc2f1 to your computer and use it in GitHub Desktop.

Original was from Reduce Advanced of funfunfunction. It was a great example, but I thought it could use a bit more of the ES6 goodness like template literals, destructuring, and the spread operators.

Also the reduced form is a more "pure" functional implementation since it doesn't mutate the original object with evil functions like push, but instead returns new data every time. A JS Bin is available to run and play with the modified version.

mark johansson waffle iron 80 2
mark johansson blender 200 1
mark johansson knife 10 4
Nikita Smith waffle iron 80 1
Nikita Smith knife 10 2
Nikita Smith pot 20 3
import fs from 'fs'
var output = fs.readFileSync('data.txt', 'utf8')
.trim()
.split('\n')
.map(line => line.split('\t'))
.reduce((customers, line) => {
customers[line[0]] = customers[line[0]] || []
customers[line[0]].push({
name: line[1],
price: line[2],
quantity: line[3],
})
return customers
}, {})
console.log(JSON.stringify(output, null, 2))
const input = `mark johansson,waffle iron,80,2
mark johansson,blender,200,1
mark johansson,knife,10,4
Nikita Smith,waffle iron,80,1
Nikita Smith,knife,10,2
Nikita Smith,pot,20,3`;
const output = input
.split('\n')
.map(line => line.split(','))
.reduce((customers, [customerName, name, price, quantity]) => ({
...customers, [customerName]: [...customers[customerName] || [],
{ name, price, quantity }]
}),
{});
console.log(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment