简体   繁体   中英

What is the right way to use the “in” operator to compile a histogram?

I'm working on implementing a histogram function for arrays in order to return an object that counts how many times an item appears in that array. However whenever I run this code I'm hit by an error message that suggests that the "in" operator cannot be used to search within the object.

var histogram = function(collection) {
  collection.reduce(function(combine, item){
    if(item in combine){
    combine[item]++;
    } else{
    combine[item] = 1;
    }
  }, {});
}
var arr = "racecar".split("");
console.log(hist(arr));

I'm guessing the problem here caused by either in or reduce but I can't figure out which it is. Any ideas?

A couple of things: 1) hist isn't the function name, 2) you're not returning anything from the function. I'm not sure how you're getting that error if you're not even calling the function properly, and something the console log would have warned you about.

var histogram = function(collection) {
  return collection.reduce(function(combine, item) {
    if (item in combine) {
      combine[item]++;
    } else {
      combine[item] = 1;
    }
    return combine;
  }, {});
}

DEMO

Here's a shorter version that doesn't rely on the use of in :

var histogram = function(collection) {
  return collection.reduce(function (combine, item) {
    combine[item] = (combine[item] || 0) + 1;
    return combine;
  }, {});
}

DEMO

The problem with in operator is that it searches not only in array indexes, but also in all inherited properties of an Array object.

var ar = [];

'toString' in ar; // prints true
'length' in ar; // prints true

When used in an incorrect context (looking for indexes in an array) it may introduce potential problems that are hard later to debug.

In your case the best is to use Array.prototype.indexOf() or Array.prototype.includes() (from ES6).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM