大家有什么好的去重方法也可以分享一下
方法1
// 升序后去重
const arr = [1,1,2,3,4,5,65,5,6,7,31,23,33,33,21];
let newarr = arr.sort((a,b) => a-b); // 升序
function createWeight(arr){
let result = [];
for(let i = 0; i < arr.length; i ++){
if( result.indexOf(arr[i]) < 0){
result.push(arr[i])
}
}
return result;
}
const a = createWeight(arr);
console.log( a );
方法2
// 升序后去重
const arr = [1,1,2,3,4,5,65,5,6,7,31,23,33,33,21];
let newarr = arr.sort((a,b) => a-b); // 升序
function createWeight(arr){
let obj = {};
let result = [];
for(let i = 0; i < arr.length; i ++){
if( !obj[arr[i]] ){
obj[arr[i]] = 1;
}
}
for(let item in obj){
result.push(Number(item))
}
return result;
}
const a = createWeight(arr);
console.log( a );
方法3
// 升序后去重
const arr = [1,1,2,3,4,5,65,5,6,7,31,23,33,33,21];
let newarr = arr.sort((a,b) => a-b); // 升序
const arr1 = [...new Set(newarr)];
console.log( arr1 );
方法4
// 升序后去重
const arr = [1,1,2,3,4,5,65,5,6,7,31,23,33,33,21];
let newarr = arr.sort((a,b) => a-b); // 升序
let obj = {};
for (const item of arr) {
if( !obj[item] ){
obj[item] = 1;
}
}
console.log( Object.keys(obj).join(' ') )