0

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.

  • 1
    The ternary is `acc[cv] ? acc[cv]+1 : 1`. `...acc` is spreading in other properties, `[cv]:` is a computed property name. – ASDFGerte Nov 10 '19 at 16:29

3 Answers3

1
const count = interviews
  .reduce((resultObject, interview) => {
    // We are creating an object through the reduce function by iterating through the interviews array.
    // At each iteration we will modify the result object according to the current array interview item value
    return {
      // First we copy the object we have so far
      ...resultObject,
      // Then we set the property corresponding to the current item 
      [interview]: resultObject[interview] 
        // If it is not the first time we have seen this item, the object property already exists and we update it by adding one to its value
        ? resultObject[interview] + 1 
         // Otherwise we create a new property and set it to one
        : 1
    }
  }, {})
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19
0

The truthy (or falsy) value is coming from here: acc[cv] and if there's a value you increment it by one, otherwise you set it to one.

acc[cv] is a computed property and will look up the value of cv as a property of acc, eg acc['smart city'].

Andre Nuechter
  • 2,141
  • 11
  • 19
0

The spread syntax and the conditional operator are completely unrelated here. Let's unfold back to forth here:

  1. The entire conditional operator expression is 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.
  2. The result of the conditional operator is assigned to a property in an object.
  3. The property name is [cv] - a computed property name that will equal the current value of cv.
  4. The property name and value are added to an object.
  5. The rest of the object values are ...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;
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67