Reputation: 21
I'm trying to interpret this code which is used to Sum all the values in the last column
rows.map(r => r[Object.keys(r)[Object.keys(r).length - 1]]).reduce((a, b) => a + b, 0);
What does it mean ? Can anyone suggest how can I rewrite this to give just the latest value in the last column ?
Upvotes: 2
Views: 668
Reputation: 19289
Consider if rows
was:
rows = [
{"a": 1, "b": 2, "c": 3},
{"a": 4, "b": 5, "c": 6}
];
The code is saying: for the 'last' column (which is c
) sum the values in column c
.
This bit:
Object.keys(r).length - 1
Establishes the number of properties in each row 'object' i.e. the 'last' column is the 'last' property and by using -1
you know the index of the key. In the example each row has 3 columns and the index of c
is 2.
This bit:
Object.keys(r)[Object.keys(r).length - 1]
Then returns the value c
because it is at index 2 in the list of keys in each row object (assuming each row object has similarly named and ordered keys).
So the whole thing:
rows.map(r => r[Object.keys(r)[Object.keys(r).length - 1]]).reduce((a, b) => a + b, 0);
Is just saying the same as:
rows.map(r => r["c"]).reduce((a, b) => a + b, 0);
Except c
has to be figured out - presumably you use this code and do not know the key for the 'last column'.
So to find the last value of the last column you don't need the reduce
function you just want to know the number of rows in the array and deduct 1 to get the index e.g.:
rows.map(r => r[Object.keys(r)[Object.keys(r).length - 1]])[rows.length - 1]
const rows = [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}];
const finalColumnSum = rows.map(r => r[Object.keys(r)[Object.keys(r).length - 1]]).reduce((a, b) => a + b, 0);
const finalValue = rows.map(r => r[Object.keys(r)[Object.keys(r).length - 1]])[rows.length - 1];
console.log(`Last column sum: ${finalColumnSum}`);
console.log(`Last column/ row value: ${finalValue}`);
Upvotes: 2