This is more of a… “is there a” (read: What is the) “more efficient way of doing this” question.
I have a restricted environment that I do not control. Pure Javascript only.
I have an array of associative indexes as strings. ['astring','bstring','cstring',....]
I have an object that may or may not contain those indexes as properties, along with other properties not contained in the indexes. { "astring": "12", "cstring":"20","wark": "Hrmbubble."}
The value of an indexed property in the object will contain an integer string.
Is there a better way to sum the value of the selected indexes, short of foreaching the array?
Yes there is, you can filter for the appropriate fields from the object, and pass them through a sum operation.
var propsToSum = ['astring','bstring','cstring'];
var obj = {
"astring": "12",
"cstring":"20",
"wark": "Hrmbubble."
};
var sum = propsToSum
.map(prop => obj[prop])
.filter(hasValue => hasValue)
.map(value => Number(value))
.reduce((a, b) => a + b);
console.log(sum); // 32
The map gets the appropriate values from the object.
The filter removes any undefined values from when the property wasn’t found.
The second map turns the strings into a number.
And the reduce adds the numbers together.
[quote=“alperquin, post:4, topic:293896, full:true”]
That code is a overcomplicated misuse of array methods. Why would you use 4 loops to calculate the sum?[/quote]
Because raw calculation performance is of a lower priority than pipelining, which gives clear intent in the code, making it easier to understand and modify.
My mistake, I posted the wrong variant. This version should work.var sum = propsToSum.reduce((total, prop) => total + (Number(obj[prop]) || 0), 0);
console.log(sum)
[quote=“alperquin, post:9, topic:293896, full:true”]
My mistake, I posted the wrong variant.[/quote]
Thanks, according to my tests using jsperf the functional code is only 27% slower.
Separate tests using the console timer reports that both sets of code take 0ms to run against 100 entries.
Performance is not a factor here, or in any reasonable use-case.