如果javascript中存在重复,则从数组中删除所有重复和原始元素

时间:2015-10-26 07:43:08

标签: javascript jquery

var techologylist=[1,2,2,3,4,4,5]
var newtechologylist=[];
$.each(techologylist, function (i, el) {
   if ($.inArray(el, newtechologylist) === -1) newtechologylist.push(el);
});
console.log(newtechologylist)

我想从techologylist中删除值,如果相同的2值。在我的示例2和4来两次,因此我想从数组中删除2和4 我希望结果为[1,3,5]

但我的代码的结果当然会将结果显示为[1,2,3,4,5]

如果发生重复,如何更改我的脚本以删除这两个值

1 个答案:

答案 0 :(得分:1)

var techologylist = [1, 2, 2, 3, 4, 4, 5]
var newtechologylist = [];

$.each(techologylist , function (i, el) {
    
    if ($.inArray(el, newtechologylist ) === -1) {
        newtechologylist.push(el);
    } 
    
    else {
        var index = newtechologylist.indexOf(el);
        if(index > -1){
           newtechologylist.splice(index, 1);
        }
    }
});

document.write(newtechologylist);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>