Reputation: 117
I'm newbie, and also my English in't that good. My problem is that i'm trying to build an object table from array, but with no succes. The goal is to build simple invoice script but im stuck. Let's say i have an array with some positions:
recordArr = [value, valueWithTax, taxInPercent]
I want to build an object array that sum positions (value, valueWithTax) by key "taxInPercent". What i did for now is:
for(key in recordArr){
if ( isNaN(SortrRecordArr[recordArr[key][2]]) ) {
SortrRecordArr[recordArr[key][2]] = [recordArr[0], recordArr[1]]
}
else {
newValue = SortrRecordArr[recordArr[key][2]][0] + recordArr[0]
newValueWithTax = SortrRecordArr[recordArr[key][2]][1] + recordArr[1]
SortrRecordArr[recordArr[key][2]] = [newValue, newValueWithTax];
}
}
But this keeps only last values that appears in recordArr
Of course i'd defined objects and variables earlier. I hope i did myself clear.
So it's like this:
Let's say i have an array:
recordArr[1] = [1 , 2 , 23]
recordArr[2] = [1 , 2 , 23]
recordArr[3] = [2 , 3 , 8]
recordArr[4] = [2 , 3 , 8]
recordArr[5] = [3 , 4 , 5]
recordArr[6] = [3 , 4 , 5]
I'm searching fo result like:
SortRecordArray[23] = [2 , 4]
SortRecordArray[8] = [4 , 6]
SortRecordArray[5] = [6 , 8]
I hope that's more clear to understand what i'm trying to do.
Thanks for advice, and please be gentle.
Upvotes: 0
Views: 87
Reputation: 13421
You should check with .hasOwnProperty() if item exist in an object.
And here is the whole edited code you need,
var recordArr = [];
var SortrRecordArr = [];
recordArr[1] = [1 , 2 , 23];
recordArr[2] = [1 , 2 , 23];
recordArr[3] = [2 , 3 , 8];
recordArr[4] = [2 , 3 , 8];
recordArr[5] = [3 , 4 , 5];
recordArr[6] = [3 , 4 , 5];
for(var key in recordArr){
if (!SortrRecordArr.hasOwnProperty(recordArr[key][2])) {
SortrRecordArr[recordArr[key][2]] = [recordArr[key][0], recordArr[key][2]];
} else {
newValue = SortrRecordArr[recordArr[key][2]][0] + recordArr[key][0];
newValueWithTax = SortrRecordArr[recordArr[key][2]][3] + recordArr[key][4];
SortrRecordArr[recordArr[key][2]] = [newValue, newValueWithTax];
}
}
console.log(SortrRecordArr)
Upvotes: 1