I’m having trouble converting, summing, and sorting the following arrays into key and value objects
Data Array
JavaScript
x
5
1
0: {No: '1', Product Name: 'Harry Potter', Type: 'Novel', Price: '120', Url: 'https://harry-potter'}
2
1: {No: '2', Product Name: 'Harry Potter', Type: 'Novel', Price: '100', Url: 'https://harry-potter'}
3
2: {No: '3', Product Name: 'Naruto', Type: 'Comic', Price: '68', Url: 'https://naruto'}
4
n: {No: '...', Product Name: '...', Type: '...', Price: '...', Url: '...'}
5
my current code
JavaScript
1
20
20
1
let counts = myRows.reduce((prev, curr) => {
2
let count = prev.get(curr["Product Name"]) || 0;
3
prev.set(
4
curr["Product Name"],
5
parseFloat(curr["Product Name"]) + count,
6
curr["Url"]
7
);
8
return prev;
9
}, new Map());
10
11
// then, map your counts object back to an array
12
let reducedObjArr = [counts].map(([key, value, link]) => {
13
return { key, value, link };
14
});
15
16
// SORT BY DESCENDING VALUE
17
var desc = reducedObjArr.sort((a, b) => b.value - a.value);
18
19
console.log(desc);
20
and the result of my current code
JavaScript
1
9
1
0:
2
key: "Harry Potter"
3
link: undefined
4
value: 220
5
1:
6
key: "Naruto"
7
link: undefined
8
value: 68
9
though, the result I want is like this
JavaScript
1
9
1
0:
2
key: "Harry Potter"
3
link: "https://harry-potter"
4
value: 220
5
1:
6
key: "Naruto"
7
link: "https://naruto"
8
value: 68
9
Advertisement
Answer
Map.prototype.set()
only takes 2 arguments, you’re passing 3. If you want to store multiple values in a map key, store them as an array or object. In my code below, I store [price, url]
.
Another problem is that you were trying to parse curr["Product Name"]
as the price, but it should be curr.Price
.
JavaScript
1
30
30
1
const myRows = [
2
{No: '1', "Product Name": 'Harry Potter', Type: 'Novel', Price: '120', Url: 'https://harry-potter'},
3
{No: '2', "Product Name": 'Harry Potter', Type: 'Novel', Price: '100', Url: 'https://harry-potter'},
4
{No: '3', "Product Name": 'Naruto', Type: 'Comic', Price: '68', Url: 'https://naruto'}
5
];
6
7
let counts = myRows.reduce((prev, curr) => {
8
let count = prev.get(curr["Product Name"])?.[0] || 0;
9
prev.set(
10
curr["Product Name"],
11
[parseFloat(curr.Price) + count,
12
curr.Url
13
]
14
);
15
return prev;
16
}, new Map());
17
18
// then, map your counts object back to an array
19
let reducedObjArr = [counts].map(([key, [value, link]]) => {
20
return {
21
key,
22
value,
23
link
24
};
25
});
26
27
// SORT BY DESCENDING VALUE
28
var desc = reducedObjArr.sort((a, b) => b.value - a.value);
29
30
console.log(desc);