下面咱們進入正題~(但願能對你有幫助~小編有點皮!!哈哈哈哈哈哈)數組
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
let s = new Set(ary);
// Array.from : 將set數據結構轉成真正的數組;
return Array.from(s)
}
unique(arr);
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
let obj = {};
for(let i=0;i<ary.length;i++){
let cur = ary[i];
if(obj[cur]){
//ary.splice(i,1);// 致使數組塌陷
ary[i]=ary[ary.length-1];
ary.length--;// 刪除最後一項
i--;
continue;
}
obj[cur]=cur;// 給obj新增鍵值對;屬性名和屬性值是同樣的
}
}
unique(arr);
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
let newAry = [];
for(let i=0;i<ary.length;i++){
let cur = ary[i];
if(newAry.indexOf(cur)===-1){
newAry.push(cur);
}
}
return newAry;
}
unique(arr)
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
let a = ary.sort(function (a,b) {
return a-b;
});
for(let i=0;i<a.length;i++){
if(a[i]===a[i+1]){
a.splice(i+1,1);
i--;
}
}
return a;
}
unique(arr)
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
let newAry = [];
let len = ary.length;
for(let i=0;i<len;i++){
let cur = ary[i];
if(!newAry.includes(cur)){
newAry.push(cur);
}
}
return newAry;
}
console.log(unique(arr));
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
let obj = {};
return ary.filter(function (item,index,a) {
// item : 數組每個成員
// index: 成員對應的索引
// a : 整個數組
// hasOwnProperty來校驗的該屬性是否出現過;
return obj.hasOwnProperty(typeof item+item)?false:obj[typeof item+item]=true;
if(obj.hasOwnProperty(typeof item+item)){
return false
}else{
obj[typeof item+item]=true;
return true;
}
})
}
console.log(unique(arr))
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
return ary.filter(function (item,index,a) {
return ary.indexOf(item)===index;
})
}
console.log(unique(arr));
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
for(let i=0;i<ary.length;i++){
for(j=i+1;j<ary.length;j++){
if(ary[i]===ary[j]){
ary.splice(j,1);
j--;
}
}
}
return ary;
}
unique(arr);
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
let len= ary.length;
ary = ary.sort(function (a,b) {
return a-b;
});
function loop(index) {
if(index>=1){
if(ary[index]===ary[index-1]){
ary.splice(index,1);
}
loop(index-1)
}
}
loop(len-1);
return ary;
}
console.log(unique(arr));
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
let newAry =[];
let map = new Map();
for(let i=0;i<ary.length;i++){
if(!map.has(ary[i])){
map.set(ary[i],true);
newAry.push(ary[i]);
}
}
}
unique(arr);
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
function unique(ary) {
// reduce : 第一個是函數,第二個參數會傳給第一次回調的prev;
return ary.reduce((prev,next)=>{
// 該函數返回值是下一次執行的prev;
return prev.includes(next)?prev:[...prev,next];
},[])
}
console.log(unique(arr));
複製代碼
let arr = [12,1,12,3,1,88,66,9,66];
let a = [...new Set(arr)];
console.log(a);
複製代碼