【问题标题】:How can I find out, how often one Value is in an array?我怎样才能找出一个值在数组中的频率?
【发布时间】:2019-06-23 08:27:19
【问题描述】:

我有一个数组,其中是值。现在我想知道值的重复频率。

我已经计算了值并创建了一个新数组。但现在我不想使用新数组作为基础,因为我已将图表的圆圈放入第一个数组 (data[i].circle) 中,我也想在这种情况下使用它们。那么有什么方法可以使用旧数组并在图表中显示一个值出现的频率?例如:1300 在数组中出现了 3 次。

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,
}]

【问题讨论】:

    标签: javascript arrays diagram


    【解决方案1】:
    1. 将费率计算到一个新的“字典”对象中,使用每个唯一值作为键:

      { “1300”:3, “1200”:1, }

    2. 使用字典中的计数更新原始数组。

    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]);

    【讨论】:

    • 如何更新原始数组?总的来说,我对 Javascript 和编码很陌生。
    • 检查我更新答案中的最后一行:data.forEach(el =&gt; el.circle = counts[el.lastEruption]); 为每个值收集计数后,我们通过在每个元素 (el) 上运行并设置其名为“circle”的新属性来更新原始数组" 计数 - 此值在数组中重复的次数。
    • 没有jquery有什么办法吗?我的代码中还没有它,我想把它排除在外。
    • 没有 jQuery,纯 JS。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2011-04-11
    • 1970-01-01
    • 2019-11-25
    • 2015-12-16
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多