基本数据类型方式一
filter+indexOf
const array = ['重庆','上海','重庆','北京'];
function unique(array) {
if (!Array.isArray(array)) {
throw new Error('必须是个数组')
}
return array.filter((item,index)=> array.indexOf(item)===index)
}
const res = unique(array)
console.log(res);
基本数据类型方式二
相邻元素排序
const array = ['重庆','上海','重庆','北京'];
function unique(array) {
if (!Array.isArray(array)) {
throw new Error('必须是个数组')
}
array = array.sort()
let res = [];
for (let i = 0; i < array.length; i++) {
if (array[i] !== array[i-1]) {
res.push(array[i])
}
}
return res;
}
const res = unique(array)
console.log(res);
基本数据类型方式三
Set+解构赋值
const array = ['重庆','上海','重庆','北京'];
function unique(array) {
if (!Array.isArray(array)) {
throw new Error('必须是个数组')
}
return [...new Set(array)]
}
const res = unique(array)
console.log(res);
基本数据类型方式四
Set+Array.from
const array = ['重庆','上海','重庆','北京'];
function unique(array) {
if (!Array.isArray(array)) {
throw new Error('必须是个数组')
}
return Array.from(new Set(array))
}
const res = unique(array)
console.log(res);
数组对象方式一
临时对象缓存数组项key值
const array = [{city:'重庆',picke:'546'},{city:'上海',picke:'367'},{city:'北京',picke:'546'}];
function unique(array,key) {
if (!Array.isArray(array)) {
throw new Error('必须是个数组')
}
let result = []
let temp = {}
for (let i = 0; i < array.length; i++) {
let keyName = array[i][key];
if (temp[keyName]) {
continue;
}
temp[keyName] = true
result.push(array[i])
}
return result;
}
const res = unique(array,'picke')
console.log(res);
数组对象方式二
[].reduce+缓存对象
const array = [{city:'重庆',picke:'546'},{city:'上海',picke:'367'},{city:'北京',picke:'546'}];
function unique(array,key) {
if (!Array.isArray(array)) {
throw new Error('必须是个数组')
}
let cacheObj = {}
return array.reduce((prve,current)=>{
cacheObj[current[key]]?"":cacheObj[current[key]]=true&&prve.push(current);
return prve;
},[])
}
const res = unique(array,'picke')
console.log(res);