ceghap
8/17/2017 - 9:29 AM

Use of reduce in js & fs in nodejs

Use of reduce in js & fs in nodejs

Disclaimer: this is my first time creating gist and push to gistlog.

Use of reduce() in JS

This is an example of using reduce() in JS. The this example show how to read a file (.txt) using nodejs function, fs.

reduce.js

import fs from 'fs';

var output = fs.readFileSync('data.txt', 'utf8')
.trim()
.split('\n')
.map( line => line.split(','))
.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));

data.txt

mark johansson,waffle iron,80,2
mark johansson,blender,80,1
mark johansson,knife,80,4
nikita Smith,waffle iron,80,1
nikita Smith,knife,80,2
nikita Smith,pot,80,3