數組去重通常是咱們面試中必問的題目,那如何實現數組去重,下面就讓咱們來看看javascript
Set
方法實現數組去重var arr = [1, 2, 3, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 7] console.log([...new Set(arr)]) console.log(Array.from(arr))
function fn(arr) { if (!Array.isArray(arr)) { return } var newArr = [] for (var i = 0; i < arr.length; i++) { if (newArr.indexOf(arr[i]) === -1) { newArr.push(arr[i]) } } return newArr } var res = fn(arr) console.log(res)
function fn(arr) { for (var i = 0; i < arr.length; i++) { for (var j = i + 1; j < arr.length; j++) { if (arr[i] === arr[j]) { arr.splice(j, 1) j-- } } } } fn(arr) console.log(arr)
function fn(arr) { if (!Array.isArray(arr)) { return } var newArr = [] for (var i = 0; i < arr.length; i++) { if (!newArr.includes(arr[i])) { newArr.push(arr[i]) } } return newArr } var res = fn(arr) console.log(res)