Search code examples
javascriptarraysloopsjavascript-objectsincrement

Incrementing a value in an object


I'm working on finding the mode for a given array. The way I've gone about it so far is to reduce the array into object keys, and set each of the key values to zero. Now I want to scan the array again and increment the value by 1 for each occurrence of the element in the array.

I have what I think should work, but the key with multiple occurrences isn't getting incremented. All values just read as 1.

My code so far:

const mode = function(arr) {
    const reducer = arr.reduce((accumulator, currentValue) => (accumulator[currentValue] = 0, accumulator), {});
    for (let key in reducer) {
      for (let i = 0; i < arr.length; i++) {
        if (reducer[key] === arr[i]) {
        reducer[key]++;
      }
    }
  }
  return reducer;
};

console.log(mode([6,2,3,4,9,6,1,0,5]));

Which returns:

{ '0': 1, '1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, '9': 1 }

What am I missing to change '6': 1 to '6': 2 ?

Any guidance is appreciated. Still getting the hang of things, open to any suggestions or feedback. Thank you!


Solution

  • The error in your code (as noted by @Pointy) is the comparison reducer[key] === arr[i] that should be if (key === arr[i]) {. Since you are using strict equality (===) you'll need to cast the key to a number, or use the equality (==) operator instead.

    const mode = function(arr) {
      const reducer = arr.reduce((accumulator, currentValue) => (accumulator[currentValue] = 0, accumulator), {});
      for (let key in reducer) {
        for (let i = 0; i < arr.length; i++) {
          if (+key === arr[i]) {
            reducer[key]++;
          }
        }
      }
      return reducer;
    };
    
    console.log(mode([6, 2, 3, 4, 9, 6, 1, 0, 5]));

    However, you are doing some redundant work, since you can compute the number of occurrences when you reduce the array to an object:

    const mode = function(arr) {
      return arr.reduce((accumulator, currentValue) => {
        accumulator[currentValue] = (accumulator[currentValue] ?? 0) + 1;
        
        return accumulator;
      } , {});
    };
    
    console.log(mode([6,2,3,4,9,6,1,0,5]));