javascript - Splicing Array Based on For Loop Iteration -
i trying take array ('selectedworkshops'), , move objects in 'registeredworkshops'. then, want remove objects both 'selectedworkshops' , array called 'workshops'.
see codepen here: http://codepen.io/truescript/pen/wbvqnn
arrays:
var workshops = [ { name: 'apples', workshopid: '19' }, { name: 'oranges', workshopid: '3b' }, { name: 'pears', workshopid: 'x6' }, { name: 'pineapples', workshopid: '55' }, { name: 'watermelons', workshopid: '8v' } ]; var selectedworkshops = [ { name: 'oranges', workshopid: '3b' }, { name: 'watermelons', workshopid: '8v' }, { name: 'pears', workshopid: 'x6' } ]; var registeredworkshops = [];
function supposed move workshops 'registeredworkshops' , remove them 'selectedworkshops' , 'workshops':
flipworkshops = function(){ var numberofworkshops = selectedworkshops.length; var x = 1; for(var = 0; < numberofworkshops; i++ ){ registeredworkshops.push(selectedworkshops[i]); for(var j = 0, arraylength = workshops.length; j < arraylength; j++) { var selectedworkshop = selectedworkshops[i]; var originalworkshop = workshops[j]; if(selectedworkshop == originalworkshop){ var matchingworkshop = j; workshops = workshops.splice(j, 1); selectedworkshops = selectedworkshops.splice(i, 1); } } } }; flipworkshops();
why aren't objects being spliced out of 'workshop' , 'selectedworkshops' arrays should be? doing wrong?
"the splice() method adds/removes items to/from array, , returns removed item(s)." http://w3schools.com/jsref/jsref_splice.asp so, basically, you're reducing workshops single object, removed array element.
instead, change:
workshops = workshops.splice(j, 1); selectedworkshops = selectedworkshops.splice(i, 1);
...to:
workshops.splice(j, 1); selectedworkshops.splice(i, 1);
maybe want:
var registeredworkshops = []; var flipworkshops = function(){ var numberofworkshops = selectedworkshops.length; var x = 1; for(var = numberofworkshops - 1; >= 0; i-- ){ registeredworkshops.push(selectedworkshops[i]); var selectedworkshop = selectedworkshops[i]; for(var j = workshops.length - 1; j >= 0; j--) { var originalworkshop = workshops[j]; if(selectedworkshop.name == originalworkshop.name && selectedworkshop.workshopid == originalworkshop.workshopid){ var matchingworkshop = j; workshops.splice(j, 1); selectedworkshops.splice(i, 1); } } } }; flipworkshops();
fixed splice
, reversed loop, suggested jwatts1980, moved selectedworkshop
var out of loop, , compared each object item, rather comparing objects, since objects don't compare.
Comments
Post a Comment