数组去重
indexof
判断元素是否在数组中,有就返回元素的索引,没有返回-1
新建一个空的结果数组,for循环元素组,判断结果数组是否存在该元素,存在跳过,不存在就push
<script>
;(function () {
function unique(){
let newArr = [];
// this表示arr
for(let i = 0; i<this.length; i++){
// this[i]表示数组中的每一个元素
if(newArr.indexOf(this[i]) != -1 ){
}else{
newArr.push(this[i])
}
}
return newArr;
}
Array.prototype.unique = unique;
}())
let arr = [1,2,3,3,2,1,1,2,5,1,9,10,10,3]; // => [1,2,3]
let newArr = arr.unique();
console.log(newArr) // => [1,2,3]
</script>
空对象添加属性
利用对象的属性不能重复的特点(可能有问题,不建议用)
<script>
; (function () {
function unique() {
let newArr = [];
let o = {};
for (let i = 0; i < this.length; i++) {
var t = this[i]
if (o[t]) { }
else {
newArr.push(t);
o[t] = true
}
}
return newArr
}
Array.prototype.unique = unique
}())
let arr = [1, 2, 3, 3, 2, 1, 1, 2, 5, 1, 9, 10, 10, 3];
let newArr = arr.unique()
console.log(newArr);
</script>
双重for循环,配合splice去重
<script>
; (function () {
function unique() {
let newArr = this
for (let i = 0; i < this.length; i++) {
for(let j=i+1;j<this.length;j++){
if(this[i]==this[j]){
newArr.splice(j,1)
j--
}
}
}
return newArr
}
Array.prototype.unique = unique
}())
let arr = [1, 2, 3, 3, 2, 1, 1, 2, 5, 1, 9, 10, 10, 3,7];
let newArr = arr.unique()
console.log(newArr);
</script>
sort排序
先使用sort() 方法进行排序,然后排序数组进行遍历,比较相邻元素。
<script>
; (function () {
function unique() {
let arr = this.sort(); // 排序后,把相同的元素放在一起
let newArr = [arr[0]]
for (let i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
newArr.push(arr[i])
}
}
return newArr;
}
Array.prototype.unique = unique;
}())
let arr = [1,2,3,3,2,1,5,4,2,1,2,4,8,4];
let newArr = arr.unique();
console.log(newArr)
</script>
ES6中的set
set学习:https://www.jianshu.com/p/80bf2e6139dc
<script>
let arr = [1,2,3,3,2,1,1,2,5,1,9,10,10,3];
let newArr = [...new Set(arr)]
console.log(newArr)
</script>
let newArr = new […new Set(arr)]
统计数组元素
hasOwnProperty判断自身属性是否存在
<script>
function fn(arr){
let obj = {};
for(let i =0;i<arr.length;i++){
let t = arr[i];
if(obj.hasOwnProperty(t)){
obj[t] +=1;
}else{
obj[t]=1
}
}
return obj;
}
let arr = [1,2,3,4,3,2,6,7,3,9,5];
let res = fn(arr);
console.log(res);
</script>
数组的交并差集
交集
…展开数组,Set 去重
concat方法用于连接两个或多个数组
<script>
let arr1 = [1,2,3,3]
let arr2 = [4,5,6,3,2,4,9]
function union(arr1,arr2){
// let res = new Set([...arr1,...arr2])
let res = new Set(arr1.concat(arr2))
return res
}
console.log(union(arr1,arr2));
</script>
并集
filter自带遍历 过滤器
<script>
function intersection(arr1,arr2) {
let s1 = new Set(arr1);
let s2 = new Set(arr2);
let newArr = [...s1].filter(item=>{
return s2.has(item)
})
return newArr;
}
let arr1 = [1,2,3]
let arr2 = [3,4,5]
console.log(intersection(arr1,arr2));
</script>
差集
<script>
let arr1 = [1,2,3];
let arr2 = [3,4,5]; // arr1 - arr2 arr2 - arr1 不一样
function minus(arr1,arr2) {
let s1 = new Set(arr1);
let s2 = new Set(arr2);
let newArr = [...s1].filter(item=>{
return !s2.has(item)
})
return newArr
}
console.log(minus(arr1,arr2)) // [1,2]
console.log(minus(arr2,arr1)) // [4,5]
</script>