常用Javascript数组去重复方法 约定不等于承诺〃 2022-09-05 14:51 205阅读 0赞 方法一(filter): function unique(arr1) { const res = new Map(); return arr1.filter((a) => !res.has(a.siteId) && res.set(a.siteId, 1)) } function unique(array) { return array.filter(function(item, index, array){ return (item && !isNaN(item) &&array.indexOf(item) === index); }); } 方法二(indexOf): function unique(array) { let res = []; const len = array.length; for (let i = 0; i < len; i++) { let current = array[i]; if (res.indexOf(current) === -1) { res.push(current) } } return res; } 方法三(splice): function unique(array) { const len = array.length; for (let i = 0; i < len;) { if (array[i] === array[i + 1]) { array.splice(i + 1, 1); } else { i++; } } return array; } 方法四(sort): function distinct(array) { var res = []; var sortedArray = array.concat().sort(); var seen; for (var i = 0, len = sortedArray.length; i < len; i++) { // 如果是第一个元素或者相邻的元素不相同 if (!i || seen !== sortedArray[i]) { res.push(sortedArray[i]) } seen = sortedArray[i]; } return res; } 方法五(hasOwnProperty): function unique(arr) { var obj = {} return arr.filter(function(item, index, array){ return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true) }) }
还没有评论,来说两句吧...