Skip to content

Instantly share code, notes, and snippets.

@ricokahler
Created April 7, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricokahler/4d1056c8b7f0ec43f0540301106cac44 to your computer and use it in GitHub Desktop.
Save ricokahler/4d1056c8b7f0ec43f0540301106cac44 to your computer and use it in GitHub Desktop.
map - reduce in javascript
class Something {
foo: string;
bar: string;
x: number;
constructor(x: number) {
this.x = x;
this.foo = 'foo';
this.bar = 'bar';
}
}
const objects = [new Something(0), new Something(1), new Something(2)];
const xOfObjects = objects.map(function(object) {
return object.x;
});
console.log(xOfObjects);
const sumOfXs = objects
.map(obj => obj.x)
.reduce(function(sum, nextItem) {
return sum + nextItem;
}, 0);
console.log(sumOfXs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment