简体   繁体   中英

How to push arrays into an associative array, and then retrieve the values for comparison?

My problem is that I want to create an array, to hold multiple arrays that I can compare with each other. This will be used for check boxes changes across multiple pages at the same time.

So for example I'd like to have:

masterArray = [];
masterArrayChanged = [];

Then to be able to do this:

masterArray["pageName"][ARRAY OF CHECKBOXES HERE]
masterArrayChanged["pageName"][ARRAY OF CHECKBOXES HERE ];
On user checkbox click => masterArrayChanged["pageName"].push({thisCheckBox});

So that later I can go and compare the two arrays to see if the user made changes:

jQuery.grep(masterArrayChanged["pageName"], function(el) {
        if (jQuery.inArray(el, masterArray["pageName"]) == -1) alert(el);
});

Any idea if this is doable? Or if there is a better way of achieving what I want?

Ok I think I answered my own question. Please correct me if this is wrong, or if there is a more efficient way to do this:

  var pagename,
  masterArrayChanged= [],
  masterArray = [];



var updateFunc = function(checkBox,action,page){
      if(action === 'add') {
        masterArrayChanged[page].push({ checkBox });
      }
      else {
        masterArrayChanged[page].splice( $.inArray(checkBox, masterArrayChanged[tabID]), 1 );        
      }
      console.dir(masterArrayChanged[page]);
    }

Yes, it's doable. Only thing is, comparing the arrays might end up being a bit resource intensive, especially if you'll be dealing with a lot of data.

So instead of two arrays, why not only have one array that keeps track of the changes that have happened? So on submit, you only check if there are any values in the array. If there are values, then you know changes were done by the user.

You might also want to give the check-boxes identifiers, so when a check-box (or check-box group) changes, you add it's identifier to the array/object and if the user undoes the changes, you remove the identifier

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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