
回复
最近在日常开发过程中,需要实现城市选择功能,同时支持模糊搜索。看似简单的功能动手实现起来却有很多难点。本篇文章详细记录开发过程中遇到的问题和对应的解决方法,希望能够帮助你,建议点赞收藏!
data?.forEach((city) => {
if (city.cityName?.includes("长沙")) {
city.letter = "CHANGSHASHI"
} else if (city.cityName?.startsWith("重庆")) {
city.letter = "CHONGQING"
} else if (city.cityName?.startsWith("厦门")) {
city.letter = "XIAMENSHI"
} else {
city.letter = pinyin4js.convertToPinyinString(city.cityName, '', pinyin4js.FIRST_LETTER).toUpperCase()
}
})
let collator = new intl.Collator();
data.sort((firstCity: HotCityBean, secondCity: HotCityBean) => {
return collator.compare(firstCity.letter, secondCity.letter)
})
let target = data[0].letter?.charAt(0) ?? ""
let cityType = new HotCityTypeBean()
cityType.name = target;
data.forEach((value, number) => {
if (value.letter?.charAt(0) != target) {
this.cityList.push(cityType)
target = value.letter?.charAt(0) ?? ""
cityType = new HotCityTypeBean()
cityType.name = target
cityType.city.push(value)
} else {
cityType.city.push(value)
}
.......
})
首先得到第一条城市的首字母 A 作为目标项,然后使用 forEach 遍历数据,如果遍历的对象的首字母和目标项 A 不相等,则先认为首字母 A 的城市遍历结束,直接将相同字母 A 的数据放入集合,否则将相同字母 A 的数据放在一起(cityType.city.push(value))。
if (number == data.length - 1) {
if (!cityType.city.includes(value)) {
cityType.city.push(value)
}
this.cityList.push(cityType)
}
List({ space: 14, initialIndex: 0, scroller: this.scroller }) {
ForEach(this.cityList, (bean: HotCityTypeBean, index: number) => {
if (index == 0) {
ListItem() {
Text() {
Span("当前城市: ")
.fontSize($r("app.float.sp_t5"))
.fontColor($r("app.color.color_S5"))
Span(this.cityName)
.fontSize($r("app.float.sp_t5"))
.fontColor($r("app.color.color_S7"))
}
}.margin({ top: $r("app.float.vp_10") })
}
ListItemGroup({ header: this.headView(bean.name) }) {
ForEach(bean.city, (item: HotCityBean, childIndex: number) => {
ListItem() {
Column() {
Text(`${item.cityName}`)
.height(44)
.fontSize($r('app.float.sp_t4'))
.width(FULL_WIDTH)
.onClick(() => {
})
if (childIndex == bean.city.length - 1) {
Divider()
.color($r('app.color.color_S3'))
.height(0.5)
.vertical(false)
}
}.alignItems(HorizontalAlign.Start)
}
}, (item: HotCityBean, childIndex: number) => `${childIndex}${new Date()}`)
}
}, (bean: HotCityTypeBean, index: number) => `${index}${new Date()}`)
} .sticky(StickyStyle.Header)
本文详细讲述了对城市数据的处理,包括对音字,首字母排序以及按首字母对数据进行分组处理,特别是分组处理这块的代码比较复杂,需要亲自动手尝试才能更好的理解,学会的小伙伴赶紧动手试试吧!如果您有更好的处理方式,欢迎评论区留言!