javascript - Remove Matching Objects from Array While Adding them to Another Array -
i trying build 3-tiered function: first, array lists available workshops (array called 'workshops'). second, array lists workshops user has selected (this array called 'selectedworkshops'). third, have final array called 'registeredworkshops'.
when function run, want objects within 'selectedworkshops' added 'registeredworkshops', want delete objects within 'selectedworkshops' both 'selectedworkshops' , matching elements 'workshops'. so, objects used exist in both 'selectedworkshops' , 'workshops', exist in 'registeredworkshops'.
here's i've got far:
addremoveworkshops = function(){ var numberofworkshops = selectedworkshops.length; for(var = 0; < numberofworkshops; i++ ){ registeredworkshops.push(selectedworkshops[i]); for(var j = 0, arraylength = workshops.length; j < arraylength; j++) { var searchterm = selectedworkshops[i].workshopid; if (workshops[j].workshopid === searchterm) { workshops = workshops.slice(j); } } selectedworkshops = selectedworkshops.slice(i); } }; addremoveworkshops();
however, function doesn't appear work properly. doesn't seem deleting correct workshops, , seems add 1 of selectedworkshops registeredworkshops. doing wrong?
here's codepen demonstration: http://codepen.io/truescript/pen/ggvwmx
if it's not possible add other properties objects (as per my other answer) i'd tackle this:
function registration(workshops, selected, registered) { // add selected workshops registered selected.foreach(function(workshop) { registered.push(workshop); }); // remove them other lists registered.foreach(function(workshop) { removeworkshop(selected, workshop); removeworkshop(workshops, workshop); }); } function removeworkshop(list, workshop) { var index = list.indexof(workshop); if(index >= 0) { list.splice(index, 1); } }
the function expects each of arrays passed in arguments , modify them in place. things become clearer , easier test if move loops out functions before nesting them.
there should no reason not use indexof
method here, saves having write loop. however, if reason needed use workshopid
property locate item within list, create helper method you.
function findworkshop(list, workshop) { for(var = 0; < list.length; i++) { if(list[i].workshopid === workshop.workshopid) { return i; } } return -1; }
then amend removeworkshop
function reflect that.
function removeworkshop(list, workshop) { var index = findworkshop(list, workshop); list.splice(index, 1); }
Comments
Post a Comment