一、双重遍历去重
function onlyFigure(arr) { let newarr = []; const length = arr.length for (let i = 0; i < length; i++) { for(let j = i + 1; j < length; j++) { if(arr[i] === arr[j]) { i++; j=i; } } newarr.push(arr[i]) } console.log(arr); } onlyFigure([0,0,1,2,4,2,1,6,5]);
二、原数组下标indexOf去重
function onlyFigure(arr) { let newarr = []; for (let i = 0; i < arr.length; i++) { if(arr.indexOf(arr[i]) == i) { //console.log(arr.indexOf(arr[i])); arr.push(arr[i]); } } console.log(newarr); } onlyFigure([0,0,1,2,4,2,1,6,5]);
三、新数组indexOf去重
function only(arr) { let newarr = []; let len = arr.length; for(let i = 0 ; i < len ; i ++ ) { if(newarr.indexOf(arr[i]) === -1) { newarr.push(arr[i]) } } return newarr }
四、es6 Set去重
function onlyNum(arr) { return Array.from(new Set(arr)) }
原文地址:https://www.cnblogs.com/detanx/p/jsArrayOnly.html
时间: 2024-10-04 16:21:21