乐趣区

关于javascript:js实现数组排序并去重

遍历数组

 // 先实现冒泡排序, 后实现数组去重
function fn(arr){for(var i=0; i<arr.length-1;i++){for(var j=0;j<arr.length-1-i;j++){if(arr[j]>arr[j+1]){var temp = arr[j]
        arr[j] = arr[j+1]
        arr[j+1] = temp
      }
    }
  }
  for(var k=0;k<arr.length;k++){var c = arr[k];
    for(var l=k+1;l<arr.length;l++){if(arr[l]==c){arr.splice(l,1)
        l--
      }
    }
  }
  return arr
}

var arr = [1,2,5,6,8,9,10,6,5,7,4,3,5]
console.log(fn(arr))  //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Set(使成员是惟一且无序的值)

var arr = [1,2,5,6,8,9,10,6,5,7,4,3,5]
let c = [...new Set([...arr])].sort((a,b)=>{return a-b})
console.log(c) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
退出移动版