2017-01-13 23 views
0

我有對象[Object.id = 1, Object.id = 2, Object.id = 3, Object.id = 4, Object.id = 5]數組,我有另一個數組[Object.id = 0, Object.id = 2]如何與其他陣列添加缺少的元素過濾器陣列和替換重複項目

所以我希望看到的結果:

[Object.id = 0, Object.id = 1, Object.id = 2, Object.id = 3, Object.id = 4, Object.id = 5] 

,並在應該從第二個陣列插入Object.id = 2,並且應該跳過第一個陣列的Object.id = 2。那麼多,合併和替換操作。

+ (NSArray *)savedRecords:(NSArray *)records 
{ 
    NSArray *pendingNotPaidrecords = [self pendingNotPaidRecords]; 

    if (pendingNotPaidRecords.count == 0) { 
    return records; 
    } 

    NSMutableArray *remoterecords = [[NSMutableArray alloc] initWithArray:records]; 
    NSMutableArray *filteredrecords = [NSMutableArray new]; 

    for (Record *localrecord in pendingNotPaidrecords) { 
    record *temprecord = nil; 

    for (Record *record in records) { 
     if ([record.recordId integerValue] == [localrecord.recordId integerValue]) { 
     [remoterecords removeObjectIdenticalTo:record]; 
     temprecord = localrecord; 
     break; 
     } 
    } 

    if (temprecord) { 
     [filteredrecords addObject:temprecord]; 
    } else { 
     [filteredrecords addObject:localrecord]; 
    } 
    } 

    NSArray *combinedArray = [filteredrecords arrayByAddingObjectsFromArray:remoterecords]; 

    return combinedArray; 
} 
+0

編輯與相關的代碼顯示你已經嘗試過,並解釋你的問題是什麼問題你正擁有的。 – rmaddy

+0

@rmaddy,只是更新了一個代碼。所以我們的目標是合併兩個數組。所以如果我們有相同的記錄,我們應該從第二個數組中挑選記錄並將它們放到臨時數組中。如果記錄不存在於第一個數組中,我們只需要找到它並放入臨時數組中。 –

回答

1

也許不是最優雅的解決方案,但嘿它的作品。

var array1 = [Object(id: 1), Object(id: 2)] 
var array2 = [Object(id: 0), Object(id: 2)] 

// Keep original. 
array1.append(contentsOf: array2.filter{ a in !array1.contains{ b in b.id == a.id } }) 

// Replace original with duplicate. 
array1 = array1.filter{ a in !array2.contains{ b in b.id == a.id } } + array2 
+0

對不起,我糾正了我的自我,我在這裏使用objective-c。 Swift中的 –

+0

非常優雅,我想我們也應該在這裏保留這個答案。很好的例子 –

+0

啊,好的!而且,單線程也可以,但可能比需要更復雜一點。 – xoudini

0

這裏是我會做什麼:

// remove the ids of array2 from array1 
NSArray *array = [array1 filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (id in %@)", [array2 valueForKey:@"id"]]]; 
// add elements of array2 
array = [array arrayByAddingObjectsFromArray:array2]; 
// sort by id 
array = [array sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES]]]; 

或使用可變數組相同的過程:

NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array1]; 
// remove the ids of array2 from array1 
[mutableArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (id in %@)", [array2 valueForKey:@"id"]]]; 
// add elements of array2 
[mutableArray addObjectsFromArray:array2]; 
// sort by id 
[mutableArray sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES]]];