I do an ajax call in a lightbox script which returns a form.

when the form is loaded I call var initial = $('form').serializeArray();

when the form is submitted I call 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?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top