How to compare each record with previous record in a same list using javascript?

hi all,

as my code below, i need to compare each id record from the actions list with its previous id record within that same list. how do i do that? please help…:confused:


myFormResponse = function(responseXML) {
var product = $(responseXML).find('product');
			var status = $(product).find('status').first().text();
			if (status == "SUCCESS") {
			var actions = $(product).find('productActionsList');
			
				actions.each(function(i, v) {
					var act = $(v).find('actLocationDTO');
					var actLocId = $(act).find("id").text();
					
					//do comparison for each id with previous id
				});
			};

thanks in advanced…

You can use the i variable which refers to the current array item, to access other items such as the previous item that you are wanting to access.

hi…thanks for the reply…

actually, i tried something like this…but it seems doesnt work…

				for(var i=0;i<actions.length; i++){
					if($(act[i]).find("id").text() != $(act[i-1]).find("id").text()){
					// do something
					}
				}

You are already inside of an each loop, so doubling up on the looping by looping all over again through everything for each action, seems to be completely wasteful.

i see…than how do i make use of that -1 to get the previosu record? or i should use something else?

It might help if you were to understand what is happening in the following code:


actions.each(function(i, v) {
    ...
});

jQuery applies the function to each item in the actions object. The this keyword refers to an item in the array, the i variable is the index of the array, and the v variable is also a reference to the item in the array.

Each time that function is executed, and it will be executed on every item in the actions object, jQuery passes to the function index number of the item that the function is being run on, and a reference to the item itself.

So, since the function knows which item it is being run on, and you have the i variable, you can access the current item that the function is being run on by using this, actions[i], or v - those all refer to the same item within the actions object.

Of those, the one that uses an index reference is suitable for accessing other parts of the actions object, so you can use actions[i - 1] to refer to the item that comes before the actions[i] item. The only trouble there is when the function is being run on the first item, that being actions[0] - for actions[0 - 1] ends up being actions[-1] which is not a valid index reference, which is easily dealt with by checking first if i is greater than zero.