Question

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?

Was it helpful?

Solution

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++;
    }
}

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top