JS - 获取数组重复项
数组-获取数组重复项 ,场景一:有时候我们需要重复项,给用户二次确认数据。场景三:把相同类型数据排列在一起。场景二:只要非重复项数据。以下可以满足以上场景。
·
数组-获取数组重复项
场景一:有时候我们需要重复项,给用户二次确认数据
场景二:只要非重复项数据
场景三:把相同类型数据排列在一起
以下可以满足以上场景
//数据
const List=[
{
name:'大学女友',
age:20,
type:'正宫'
},
{
name:'隔壁姐姐',
age:24,
type:'微信'
},
{
name:'楼上阿姨',
age:32,
type:'阿姨'
},
{
name:'小区妹妹',
age:18,
type:'微信'
},
]
let key = {} //存储的 key 是type的值,value是在indeces中对应数组的下标
let indices = [] //数组中每一个值是一个数组,数组中的每一个元素是原数组中相同type的下标
List.map((item, index) => {
//根据对应字段 分类(type)
let type= item.type
let _index = key[type]
if (_index !== undefined) {
indices[_index].push(index)
} else {
key[type] = indices.length
indices.push([index])
}
})
// 归类结果
let result = []
indices.map((item) => {
item.map((index) => {
//result.push(List[index]) 相同项排序在一起
//if (item.length > 1) {} 只要重复项
//if (item.length == 1){} 只要单独项
//我这里需要重复项 根据业务处理
if (item.length > 1) {
result.push(List[index])
}
})
})
//结果
//[{ name:'隔壁姐姐',age:24,type:'微信'}, {name:'小区妹妹',age:18,type:'微信'}]
另一种数组重复处理:
对重复项处理,只要重复项其中一个提示,如下 重复名字,只提示重复的值
const realNameList = ['杨蜜','杨蜜','柳颜','柳颜','苍静空']
const realNameResult = realNameList.filter((e, i) => realNameList.indexOf(e) !== realNameList.lastIndexOf(e) && realNameList.indexOf(e) === i)
if (realNameResult.length > 0) {
alert(`以下喜欢你的人:${realNameResult.toString()}重名,请选一个翻牌!`)
}
更多推荐
已为社区贡献1条内容
所有评论(0)