简体   繁体   English

JavaScript,从数组中删除相同的项目

[英]javascript, remove identical items from array

I do an ajax call in a lightbox script which returns a form. 我在返回表格的灯箱脚本中进行ajax调用。

when the form is loaded I call var initial = $('form').serializeArray(); 加载表单时,我称var initial = $('form').serializeArray();

when the form is submitted I call var final = $('form').serializeArray(); 提交表单时,我称var final = $('form').serializeArray();

which gives me two arrays of objects, What I now want to do is compare each object in the arrays and remove those that have not changed. 这给了我两个对象数组,我现在想要做的是比较数组中的每个对象并删除那些没有改变的对象。

how would I do this? 我该怎么做?

I'm assuming that the two arrays will have equal length, and that the elements will be in the same order in both arrays. 我假设两个数组的长度相等,并且两个数组中的元素顺序相同。 In this case, what you need to do is look at each element of the first array and compare it to the corresponding element of the second array; 在这种情况下,您需要查看第一个数组的每个元素,并将其与第二个数组的对应元素进行比较; if they match, then remove the element in that position from both arrays. 如果它们匹配,则从两个数组中删除该位置的元素。

Something like this should work (though I haven't tested it): 这样的事情应该可以工作(尽管我还没有测试过):

var i = 0;
while (i < initial.length) {
    if(initial[i] == final[i]) {
        initial.splice(i,1);
        final.splice(i,1);
    }
    else {
        i++;
    }
}

The fastest way to do this I think 我认为最快的方法

var len = initial.length, i=0, changed=[];
/* I hope initial.length==final.length*/

    for(i; i<len; i++){
        /* 0== '' */
        if (initial[i]===final[i])
           changed[i] = final[i];
    }

//now play with //现在玩

changed 变了

I've got confused abou the question 我对这个问题感到困惑

does .splice() reorder the indexes? .splice()是否对索引重新排序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM