0

The accepted answer in this question very elegantly logs the number of occurrences of all values in a given array to the console. When I try to set this as a value of an input or as the text of a div it only gives the last value of the array.

I can't figure it out. Excuse my noobness.

$(document).on('click', 'button', function() {
  class Counter extends Map {
    constructor(iter, key = null) {
      super();
      this.key = key || (x => x);
      for (let x of iter) {
        this.add(x);
      }
    }

    add(x) {
      x = this.key(x);
      this.set(x, (this.get(x) || 0) + 1);
    }
  }

  results = new Counter(["john", "mark", "George", "mark", "john", "George", "john", "George", "bill"]);
  for (let [number, times] of results.entries())
    $("div").text(times + "x " + number)
});
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<button>LOG</button>
<div></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Vaggelis
  • 912
  • 5
  • 17

1 Answers1

0

In each iteration you are overriding the element's text, as a result only the final text is shown. You should store the text in a variable and use that:

$(document).on('click', 'button', function () {

  class Counter extends Map {
      constructor(iter, key=null) {
          super();
          this.key = key || (x => x);
          for (let x of iter) {
              this.add(x);
          }
      }
      add(x) {
        x = this.key(x);
        this.set(x, (this.get(x) || 0) + 1);
      }
  }

  var res = "";
  results = new Counter(["john", "mark", "George", "mark", "john", "George", "john", "George", "bill"]);
  for (let [number, times] of results.entries()){
    res += times + "x " + number;
  }
  $("div").text(res);
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>LOG</button>
<div></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59