从数组Node.js中删除重复值

时间:2015-07-03 10:59:03

标签: javascript node.js

我创建了一个表单,其中有1个下拉存储另一个下拉列表的值。但问题是下拉存储重复值。我该怎么做才能使下拉列表不显示任何冗余数据

代码如下:

<form class="form-inline" role="form" method="post" action="/assignloc">

                         <div class="form-group" style="margin-top:4%;">
                         <label for="exampleInputEmail1" class="h2color" >FE Name</label>

                           <select name="selectpicker" class="form-control">

                                <% for(var i=0;i<pic.length;i++){ %> 
                                <option value=<%=pic[i].name%>>
                                <%=pic[i].name%> </option>


                               <% } %>


                        </select>
 <label for="exampleInputEmail1" class="h2color" style="margin-left:10px;">Broker ID</label>
 <input type="text" class="form-control" placeholder="Broker Id" name="brokerid">

 <button type="submit" class="btn btn-primary btn-lg active">Assign</button>
</div>
</form>

5 个答案:

答案 0 :(得分:2)

请查看以下小提琴,了解在nodejs中删除重复数组的类似示例      https://jsfiddle.net/shreya7/rgn3y04e/

  var array= ["8","2","7","2", "6"];
  var earray = [];
     for(var i in array){
        if(earray .indexOf(array[i]) === -1){
            earray.push(array[i]);
        }
    }

  alert(earray);

答案 1 :(得分:0)

var pic= ["1","2","1","1", "1", "1", "1", "3", "4", "6", "8", "9", "2"];
var uniquePic = [];
    for(var i in pic){
        if(uniquePic.indexOf(pic[i]) === -1){
            uniquePic.push(pic[i]);
        }
    }

console.log(uniquePic);

下面是一个工作小提琴: http://jsfiddle.net/spechackers/5bf3L78L/

答案 2 :(得分:0)

您只需使用Array.filter删除重复元素

即可
var unique = arr.filter(function(elem, index, self) {
    return index == self.indexOf(elem);
})

Demo

答案 3 :(得分:0)

我认为您正在使用EMBER JS我已经为您更正了代码段

<% 
var pictList = [];
for(var i=0;i<pic.length;i++){ 
    var pictItem = pic[i].name;
    var unique = true;
    for(var j=0; j<pictList.length; j++){
        if(pictList[j] == pictItem){
            unique = false;
            return;
        }
    }
    if(unique == true){
        pictList.push(pictItem);
%> 
    <option value=<%=pic[i].name%>>
        <%=pic[i].name%> </option>


    <%} } %>

答案 4 :(得分:0)

我喜欢使用Set:

var array = [1,1,2,3,3,4,4];  //your array
var uniqueSet = new Set(array);  //unique set with no duplicates  
var arrayWitoutDuplicates = Array.from(set);  //re-convert set to array

或者简而言之:

var array = [1,1,2,3,3,4,4];
var arrayWitoutDuplicates = Array.from(new Set(array));