urbanassa
urbanassa

Reputation: 9

Uncaught TypeError: Cannot use 'in' operator to search for 'car' in undefined

I am trying to define sum object which keeps track of count of each string passed to "data" variable. The error says total is undefined. Is it not enough to declare second parameter as {} in reduce function to have total defined.

const data = [
  'car',
  'car',
  'truck',
  'truck',
  'bike',
  'walk',
  'car',
  'van',
  'bike',
  'walk',
  'car',
  'van',
  'car',
  'truck'
];
const sum = data.reduce((total, key) => {
  if (key in total) total[key]++;
  else total[key] = 1;
}, {});

Upvotes: 1

Views: 70

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36574

You need to return a value in reduce() callback which will be used as accumulator(total in this case) in the next iteration.

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
const sum = data.reduce((total,key) => {
  if(key in total) 
    total[key]++; 
  else 
    total[key] = 1; 
  return total;
  },
{});

console.log(sum)

You can also do this in one line

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
const sum = data.reduce((total, key) => ({...total, [key]: (total[key] || 0) + 1}), {});
console.log(sum)

Upvotes: 1

Related Questions