Some background for this coding problem. Our termTopics function needs to count how many times each of those topics was mentioned in the surveys, and then return an array with the number of mentions in the following order: smart city, arts funding, and then transportation.
const termTopics = (interviews) => {
const count = interviews.reduce((acc, cv) => {
return {...acc, [cv]: acc[cv] ? acc[cv]+1 : 1}
}, {})
return [count['smart city'], count['arts funding'], count['transportation']];
}
What I cannot understand is the spread operator, and how that creates a truthy statement for the ternary operator to operate with.
The spread syntax and the conditional operator are completely unrelated here. Let's unfold back to forth here:
acc[cv] ? acc[cv]+1 : 1
, so it will resolve to only acc[cv]+1
or 1
based on whether or not acc[cv]
is truthy or not.[cv]
- a computed property name that will equal the current value of cv
....acc
or the current values of the object that are spread into the object.In effect, {...acc, [cv]: acc[cv] ? acc[cv]+1 : 1}
is a shorter version of the following ES5 code:
var result = {};
//{...acc}
for (var key in acc) {
result[key] = acc[key];
}
//[cv]: acc[cv] ? acc[cv]+1 : 1
if (acc[cv]) {
result[cv] = acc[cv]+1;
} else {
result[cv] = 1;
}