I have an array(say expensesArray) of Expense
objects. expense has property like catId, amount, name etc. Now I want to do something like group by and some other clauses in SQL
. i.e in new array, my objects should be grouped based on catId and their amount should be added up.
For example, if I have 2 elements in expensesArray
with catId=2
and amount=20
for each then the new array should contain only one element with catId=2
and amount=40
.
This is the code that I have tried yet :
[groupedExpesesArray addObject:[self createExpenseModel:[expensesArray objectAtIndex:0]]];
ExpenseModel* expenseMObj = [groupedExpesesArray objectAtIndex:0];
for (int j = 1; j < expensesArray.count; j++)
{
ExpenseModel* expModel = [self createExpenseModel:[expensesArray objectAtIndex:j]];
if ([expModel.categoryID isEqual:expenseMObj.categoryID])
{
float amt = [expenseMObj.amount floatValue];
amt = amt+[expModel.amount doubleValue];
expenseMObj.amount = [NSNumber numberWithFloat:amt];
}
else
{
int index = [groupedExpesesArray indexOfObject:expModel];
if (index == NSNotFound)
{
[groupedExpesesArray addObject:expModel];
}
}
}
But I am still unable to get the desired value. So I need some guidance here on where I am going wrong here and possible resolving steps.
Edit:-
I am creating new object of Expense
in createExpenseModel:
method. and checking if it is available in groupedExpesesArray
. perhaps thats the problem. Isn't it?
Any suggestion would be appreciated.
Thanks.