1、new Set
const arr = ['哈尔滨', '齐齐哈尔', '齐齐哈尔', '牡丹江', '佳木斯']
let arr1 = [...new Set(arr)]
console.log(arr1);
2、indexOf
const arr = ['哈尔滨', '齐齐哈尔', '齐齐哈尔', '牡丹江', '佳木斯']
function indexOfArr(arr) {
if (!Array.isArray(arr)) {
throw new TypeError('arr is not Array')
}
var newArr = []
arr.forEach((item, index) => {
if (newArr.indexOf(item) === -1) {
newArr.push(item)
}
});
return newArr
}
console.log(indexOfArr(arr));
3、hasOwnProperty
const arr = ['哈尔滨', '齐齐哈尔', '齐齐哈尔', '牡丹江', '佳木斯']
function indexOfArr(arr) {
if (!Array.isArray(arr)) {
throw new TypeError('arr is not Array')
}
var newArr = []
arr.forEach((item, index) => {
if (newArr.indexOf(item) === -1) {
newArr.push(item)
}
});
return newArr
}
console.log(indexOfArr(arr));
4、reduce +includes
const arr = ['哈尔滨', '齐齐哈尔', '齐齐哈尔', '牡丹江', '佳木斯']
function reduceArr(arr){
if (!Array.isArray(arr)) {
throw new TypeError('arr is not Array')
}
return arr.reduce((start,item,index)=>{
if(!start.includes(item)){
start.push(item)
}
return start
},[])
}
console.log(reduceArr(arr));