I got this code from a friend (fiddle link below). The problem I am trying to figure out is that the array (arr1, which is an array of objects) automatically combines the amount attribute for the object at index 0 with the object at index 2 as seen in the console log. However if I stop the call to the function addByPayCodeAndLaborAcc() by commenting it out, then it logs the normal array as it should be. Please help why this is happening. Probably because of hoisting.
Here is the fiddle. http://jsfiddle.net/3ZQNg/
The console.log that I see
[Object, Object, Object, Object]
0: Object
amount: "0414:54:32"
laboracc: "1"
pcname: "a"
__proto__: Object
1: Object
2: Object
amount: "14:54:32"
laboracc: "1"
pcname: "a"
__proto__: Object
3: Object
length: 4
However the array that I have in the code is
arr1 = [
{
pcname : "a",
laboracc : "1",
amount : "04"
},
{
pcname : "b",
laboracc : "1",
amount : "777"
},
{
pcname : "a",
laboracc : "1",
amount : "14:54:32",
},
{
pcname : "c",
laboracc : "2",
amount : "23"
}];
Why is the amount attribute getting appended for the object at index 0 with that of object at index 2 automatically?
SOLUTION : I found out the reason. When objects are copied, they are copied by reference. That is the same object remains in the heap and only its reference is copied, unlike primary variable types like Number or String which are copied by value (that is a new copy is created). Initially uiqueRows is []. The first object in the selectedTotals array (with pcname a) is then copied to uniqueRows (copied by reference - thus uniqueRows[0] is now the same as selectedTotals[0]). We then add the second object to uniqueRows. When we come to the third object with the same pcname "a", summary object gets set to uniqueRows[0] (which is the same as selectedTotals[0]). Thus when summary.amount is updated actually the amount attribute of selectedRows[0] is getting updated (because they refer to the same object in the heap). The appended value hence gets reflected in the log.
Please refer to the console.logs in the updated fiddle. The logs indicate that the object returned as "summary" is the same as selectedTotals[0] hence "true" is printed in the log http://jsfiddle.net/3ZQNg/1/
In Chrome dev tools, all objects seem to return correct index position: