I never seem to understand JavaScript fully. Please explain this to me.
I have an array of objects called arr1. In this simplified example, it has only two members; name and someValue. The array is sorted by name and the content looks like this:
Harry 1
Joe 2
Joe 3
Peter 4
I want to create another array called arr2. It should hold the unique names from arr1. If a duplicate is found, the someValue is added for that name. I basically want this as content in arr2:
Harry 1
Joe 5 <-- the two values from Joe in arr1 sums up to 5
Peter 4
So I came up with the script below. The resulting arr2 is exactly what I want. However, the arr1 is also updated and that's not what I desire.
Why is this happening and how can I fix it?
var arr1 = [];
var arr2 = [];
arr1.push({name: 'Harry', someValue: 1});
arr1.push({name: 'Joe', someValue: 2});
arr1.push({name: 'Joe', someValue: 3});
arr1.push({name: 'Peter', someValue: 4});
let previousName = '';
for (var i=0;i<arr1.length;i++) {
if (arr1[i].name == previousName) {
arr2[arr2.length-1].someValue += arr1[i].someValue;
} else {
arr2.push(arr1[i]);
previousName = arr1[i].name;
}
}
/* Result arr1 is not ok:
0: Object { name: "Harry", someValue: 1 }
1: Object { name: "Joe", someValue: 5 } <-- I want the value 2 to be preserved
2: Object { name: "Joe", someValue: 3 }
3: Object { name: "Peter", someValue: 4 }
Result arr2 is ok:
0: Object { name: "Harry", someValue: 1 }
1: Object { name: "Joe", someValue: 5 }
2: Object { name: "Peter", someValue: 4 }
*/