从没有重复项的Javascript数组创建HTML下拉列表

时间:2013-05-08 02:30:06

标签: javascript arrays drop-down-menu

使用previously answered SO question作为参考,我创建了一个函数,用于从现有的javascript数组中填充HTML文档中的下拉列表。

这是HTML:

<fieldset>
    <legend>Choose action</legend>
        <p>Choose your action and click next</p><br />
            <select id="trigger"></select>
</fieldset>

这是Javascript:

var guns =
    [
        ["Smith and Wesson 500", "Revolver", "Full Frame", 50, "sada"], //model, type, frame, cal, trigger
        ["Glock 19", "Semi", "Compact", 9, "striker"],
        ["Smith and Wesson M and P Shield 9", "Semi", "Compact", 9, "striker"],
        ["Ruger Alaskan", "Revolver", "Full Frame", 44, "dao"],
        ["Ruger SR9", "Semi", "Compact", 9, "striker"],
        ["Desert Eagle", "Semi", "Full Frame", 50, "sada"],
        ["Smith and Wesson M and P Shield 40", "Semi", "Compact", 40, "striker"]
    ]   

var triggerDropdown = function(){
    var sel = document.getElementById('trigger');
    for (var i = 0; i < guns.length; i++) {
        var opt = document.createElement('option');
        opt.innerHTML = guns[i][4];
        opt.value = guns[i][4];
        sel.appendChild(opt);
        }
    };

我的挑战:

填充trigger 而不重复。此外,解决方案不能要求我永久更改guns(我发现了一些其他有用的SO帖子,但大多数都涉及首先从阵列中删除重复...在这种情况下,我没有选项)。

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以仅使用触发器创建单独的数组:

var triggers = function(guns) {
  var unique = {};

  return guns.reduce(function(current, item) {
    if (!(item[4] in unique)) {
      current.push(item[4]);
      unique[item[4]] = 1;
    }
    return current;
  }, []);
}(guns);

Demo

然后按正常情况迭代triggers

另请参阅:Array.reduce()

答案 1 :(得分:1)

构建列表时,请在本地跟踪您已使用过的密钥:

var triggerDropdown = function(){

    var already = {};
    var sel = document.getElementById('trigger');
    for (var i = 0; i < guns.length; i++) 
    {
      var val = guns[i][4];

      if (! already[val]) 
      {
        var opt = document.createElement('option');
        opt.innerHTML = val;
        opt.value = val;
        sel.appendChild(opt);

        already[val] = true;
      }
    }
};