Search code examples
javascriptarraysdiagram

How can I find out, how often one Value is in an array?


I have an array in which are Values. Now I want to find out how often the Values repeat.

I already counted the values and created a new array. But now I don't want to use the new array as base, for I have put circles for a Diagram into the first array (data[i].circle) and I would like to use them in this case as well. So is there any way, where I can use the old array and show in a Diagram how often one Value appears? For Example: 1300 is in the array three times.

init();

function init() {
  paper = Snap("#svgContainer");

  for (i = 0; i < data.length; i++) {
    data[i].circle = paper.circle(0, 0, 1);
  }
}

function showDiagram() {
  var diagrammBreite = data.length * radius * 4;
  var offsetLeft = (paperWidth - diagrammBreite) / 2;
  radius = (diagrammBreite / data.length) / 4;

  for (i = 0; i < data.length; i++) {
    xPos = offsetLeft + (4 * radius * i);

    for (j = 0; j < data[i]; j++) {
      yPos = paperHeight - (j * radius * 3) - radius;
      data[i].circle.attr({
        cx: xPos,
        cy: yPos,
        r: radius,
        color: farbe
      })
    }
  }
}

//one example out of my data array
var data = [{
  "country": "Germany",
  "lastEruption": 1300,
}]

Solution

    1. count the rates to a new "dictionary" object, using every unique Value as a key:

      { "1300": 3, "1200": 1, }

    2. update the original array with counts from the dictionary.

    var data = [
    {
      "country": "Germany",
      "lastEruption": 1300,
    },
    {
      "country": "France",
      "lastEruption": 1300,
    },
    {
      "country": "Italy",
      "lastEruption": 1100,
    },
    ];
    
    // count
    const counts = {};
    data.forEach(el => {
      const value = el.lastEruption;
      if (counts[value]) counts[value]++;
      else counts[value] = 1;
    });
    
    // update
    data.forEach(el => el.circle = counts[el.lastEruption]);