假设一个对象数组如下:
const listOfTags = [
{id: 1, label: "Hello", color: "red", sorting: 0},
{id: 2, label: "World", color: "green", sorting: 1},
{id: 3, label: "Hello", color: "blue", sorting: 4},
{id: 4, label: "Sunshine", color: "yellow", sorting: 5},
{id: 5, label: "Hello", color: "red", sorting: 6},
]
Run Code Online (Sandbox Code Playgroud)
如果标签和颜色相同,则重复输入.在这种情况下,id = 1且id = 5的对象是重复的.
如何过滤此数组并删除重复项?
我知道解决方案,您可以使用以下内容过滤一个键:
const unique = [... new Set(listOfTags.map(tag => tag.label)]
Run Code Online (Sandbox Code Playgroud)
但是多个键呢?
根据评论中的要求,这里是期望的结果:
[
{id: 1, label: "Hello", color: "red", sorting: 0},
{id: 2, label: "World", color: "green", sorting: 1}, …Run Code Online (Sandbox Code Playgroud) 我正在与iBeacons一起在AppDelegate.swift中实现CoreLocation方法(在AppDelegate中实现方法以确保App后台功能)
在“ ViewController.swift”随附的SingleView应用程序中,将数据从AppDelegate传递到ViewController以更新视图(例如UIImages,UILabels或UITableViews)的最佳实践是什么?
我已经成功实现了两种不同的方法:
1)委托,通过在AppDelegate.swift中触发Viewcontroller委托方法:
protocol BeaconLocationDelegate { func minorBeaconChanged(minorValue:NSNumber) }
var locationDelegate: BeaconLocationDelegate
locationDelegate?.minorBeaconChanged(nearestBeacon.minor)
Run Code Online (Sandbox Code Playgroud)
ViewController.swift:
在viewDidLoad方法中:
(UIApplication.sharedApplication().delegate as AppDelegate).locationDelegate = self
Run Code Online (Sandbox Code Playgroud)
(我发现这看起来很难看-将此属性声明为委托的更好方法吗?)
协议实现:
func minorBeaconChanged(minorValue: NSNumber) {
// do fancy stuff here
}
Run Code Online (Sandbox Code Playgroud)
2)通过在AppDelegate中创建对ViewController的引用:
let viewController:ViewController = window!.rootViewController as ViewController
viewController.doSomethingFancy()
Run Code Online (Sandbox Code Playgroud)
两种方法对我来说都很好用,但是我认为通过委派的第一种方法更优雅,并且在拥有多个ViewController时是更好的选择。
有什么建议吗?
appdelegate ×1
delegation ×1
dictionary ×1
filter ×1
javascript ×1
reduce ×1
swift ×1
unique ×1