我有一个从JSON
加载到NSMutableArray
的数组。其中一个条目AllowedTo
的值为New York, Florida
我还有一个从单独的JSON
到新NSMutableArray
的第二个数组,并且使用此数组,我填充UITableView
:
使用第一个数组,我想隐藏在第二个数组中不匹配的任何单元格。例如,最终结果(使用上面张贴的图像)将只有3个单元格(GRAND TOTAL,NEW YORK,FLORIDA),其余的(JUNIORS,FOODNATION等)将被隐藏。
答案 0 :(得分:0)
以下是使用filter function进行操作的示例。
let arrayOne = ["one", "two", "three", "four", "five"]
let arrayTwo = ["one", "two", "three"]
let filteredArray = arrayOne.filter({ arrayTwo.contains($0)})
print("filteredArray: \(filteredArray)")
然后我会为此创建一个函数,以便您可以根据需要调用它而无需更改原始数组。
func filterDataSource(arrayOne: [String], arrayTwo: [String]) -> [String] {
let filteredArray = arrayOne.filter({ arrayTwo.contains($0)})
return filteredArray
}
修改
Objective-C中的相同功能,有更优雅的方式,但我有点生疏:)
NSArray *arrayOne = @[@"one", @"two", @"three", @"four", @"five"];
NSArray *arrayTwo = @[@"one", @"two"];
NSMutableArray *filteredArray = [[NSMutableArray alloc] initWithCapacity:5];
for (NSString *string in arrayOne) {
for (NSString *filterString in arrayTwo) {
if ([string isEqualToString:filterString]) {
[filteredArray addObject:string];
continue;
}
}
}
答案 1 :(得分:0)
你也可以使用套装:
NSMutableSet *dataToShow = [NSMutableSet setWithArray:yourFirstArray];
NSSet *other = [NSSet setWithArray:yourSecondArray];
[dataToShow intersectSet:other];
现在“dataToShow”只包含两个数组中的项目。
修改
例如:
Array1有“1”,“2”,3“,”4“
Array2有“1”,“4”,“5”
Set1将具有Array1的元素,但可能是不同的顺序:“2”,“4”,“3”,“1
Set2相同:“4”,1“,”5“
相交的集合“dateToShow”将具有元素“1”和“4”,因为它们是两个集合中唯一存在的元素。
但是,订单无法保证,所以如果这对您很重要...我建议[dataToShow.allObjects sortedArrayUsingComparator ....];
答案 2 :(得分:0)
所以,我正在以错误的方式看待这个。我的意图是将JSON解析为一个数组,然后删除我不需要的东西。当用我想要展示的东西填充数组要简单得多。在我的JSON解析器的末尾,我添加了这个
if ([AllowedTo containsString:newEstNet.EntityName]) {
NSLog(@"%@ displayed", newEstNet.EntityName);
[listOfEstNetGrand addObject:newEstNet];
} else {
NSLog(@"%@ not displayed", newEstNet.EntityName);
// dont add the object to the array
}