Having a rough coding day today. I can't seem to figure out why this code on fiddle isn't behaving as expected.
var masterList = new Array();
var templates = new Array();
templates.push({"name":"name 1", "value":"1234"});
templates.push({"name":"name 2", "value":"2345"});
templates.push({"name":"name 3", "value":"3456"});
templates.push({"name":"name 4", "value":"4567"});
templates.push({"name":"name 1", "value":"5678"});
templates.push({"name":"name 2", "value":"6789"});
templates.push({"name":"name 3", "value":"7890"});
templates.push({"name":"name 4", "value":"8901"});
var addUnique = function(thatObj) {
var newList = new Array();
if ( masterList.length == 0 ) {
// add the first element and return
masterList.push(thatObj);
return;
}
for (j=0; j<masterList.length; j++) {
if (masterList[j].name != thatObj.name) {
newList.push(thatObj);
}
}
// store the new master list
masterList = newList.splice(0);
}
for (i=0; i<8; i++) {
addUnique(templates[i]);
}
console.log(masterList);
console.log(masterList.length);
In my (humble) opinion, it should iterate through the templates array, populate the masterList with each element of the templateArray, but only result in 4 elements in the master array, as those with the same name should be replaced rather than copied into the intermediate array. However, I'm only seeing one entry in masterList.
Where are the good old days of strongly typed languages and pointers? Sigh. It's frustrating not being able to grasp the mess JavaScript is creating (well, maybe I'm the one making the mess) but I blame JS for not understanding me...