amars
amars

Reputation: 407

Having problems with mapping forEach and Reduce onto a Map Object

This same approach works with objects when used with object values. But how do I make it work on map objects?

const one = new Map ();
one.set ('part1', {section1: 1, section2: 'one'});
one.set ('part2', {section1: 8, section2: 'eight'});
one.set ('part3', {section1: 5, section2: 'five'});

one.forEach(x => console.log(x.section1));

let temp1 = one.forEach(x => x.section1);
console.log(temp1);

let temp2 = one.forEach(x => x.section1).reduce((sum, cur) => sum + cur);
console.log(temp2);

Upvotes: 0

Views: 446

Answers (2)

Ele
Ele

Reputation: 33726

The function forEach returns undefined, so you can't call the function reduce.

Additionally, you don't need to call the function Array.prototype.map, with a reduce is just fine.

const one = new Map ();
one.set ('part1', {section1: 1, section2: 'one'});
one.set ('part2', {section1: 8, section2: 'eight'});
one.set ('part3', {section1: 5, section2: 'five'});

let temp2 = Array.from(one.values()).reduce((sum, {section1: cur}) => sum + cur, 0);
console.log(temp2);

Upvotes: 1

Ashish
Ashish

Reputation: 4330

forEach returns undefined, you need to use Array.map to get values of section1 in an array to call reduce on it.

But the problem is with Map you don't have .map property. Luckily we values.

The values() method returns a new Iterator object that contains the values for each element in the Map object in insertion order.

So I use ... over iterator in [] to get an array where I can run .map

const one = new Map ();
one.set ('part1', {section1: 1, section2: 'one'});
one.set ('part2', {section1: 8, section2: 'eight'});
one.set ('part3', {section1: 5, section2: 'five'});

let temp = [...one.values()].map(x => x.section1).reduce((sum, cur) => sum + cur);
console.log(temp);

Alternatively, you don't even need map function When you have converted your Map values to an array, you can directly call reduce

const one = new Map ();
one.set ('part1', {section1: 1, section2: 'one'});
one.set ('part2', {section1: 8, section2: 'eight'});
one.set ('part3', {section1: 5, section2: 'five'});

let tempAlt = [...one.values()].reduce((sum, {section1: cur}) => sum + cur, 0);
console.log(tempAlt);

Upvotes: 1

Related Questions