英文:
Most efficient way filtering an array
问题
以下是翻译好的代码部分:
我有一个数组的数组如下所示:
var masterArray = [
["String", "String", "String", "1"],
["String", "String", "String", "2"],
["String", "String", "String", "3"],
...
]
每个数组的最后一个元素都是一个整数字符串。
根据每个数组的最后一个元素,将主数组过滤为3个数组,最有效的方法是什么?
当然,我可以像这样做:
var filteredArray1 = [[String]]()
var filteredArray2 = [[String]]()
var filteredArray3 = [[String]]()
for anArray in masterArray {
if anArray[3] == "1" {
filteredArray1.append(anArray)
} else if anArray[3] == "2" {
filteredArray2.append(anArray)
} else if anArray[3] == "3" {
filteredArray3.append(anArray)
}
}
但我认为应该有一种更有效的方法来实现这一点,也许可以使用过滤器或谓词?我只是无法找到如何精确定位每个数组的最后一个元素。
**编辑**
只是为了举个例子,以我认为是一个高效的过滤方式。在一个不相关的用例中,我有一个CoreData实体tagRecords的数组。在这种情况下,由于我知道每个实体都有一个dateStart属性,我可以使用NSPredicate轻松地进行过滤,如下所示:
let currentPred = NSPredicate(format: "dateStart >= %@ && dateStart <= %@", argumentArray: [currentMonth.startOfMonth(), currentMonth.endOfMonth()])
let filteredRecords = tagRecords.filter { currentPred.evaluate(with: $0) }
英文:
I have a array of arrays as follows:
var masterArray = [
["String", "String", "String", "1"],
["String", "String", "String", "2"],
["String", "String", "String", "3"],
...
]
Last element of each array is an Int String.
What would be the most efficient way of filtering the master array into 3 arrays based on the last element of each array?
Of course I can do smth like this:
var filteredArray1 = [[String]]()
var filteredArray2 = [[String]]()
var filteredArray3 = [[String]]()
for anArray in masterArray {
if anArray[3] == "1" {
filteredArray1.append(anArray)
} else if anArray[3] == "2" {
filteredArray2.append(anArray)
} else if anArray[3] == "3" {
filteredArray3.append(anArray)
}
}
But I think there should be a more efficient way of achieving this, maybe with filters or predicates? I just can't figure out how to pin-point that last element of each array.
Edit
Just to give an example of what in my opinion is an efficient way of filtering.
In a different unrelated use case, I have an array of CoreData entities tagRecords. In this case, as I know that each entity has dateStart property, I can easily filter it with NSPredicate like so:
let currentPred = NSPredicate(format: "dateStart >= %@ && dateStart <= %@", argumentArray: [currentMonth.startOfMonth(), currentMonth.endOfMonth()])
let filteredRecords = tagRecords.filter { currentPred.evaluate(with: $0) }
答案1
得分: 1
A two step solution is to group the data into a dictionary and then extract each array from it using the keys (which I assume are given)
let grouped = Dictionary(grouping: masterArray, by: .last)
let filteredArray1 = grouped["1", default: []]
//...
英文:
A two step solution is to group the data into a dictionary and then extract each array from it using the keys (which I assume are given)
let grouped = Dictionary(grouping: masterArray, by: \.last)
let filteredArray1 = grouped["1", default: []]
//...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论