JavaScript 数组合并去重实现
一、数组合并
方法一、for循环实现数组合并
代码如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] for (let i in arr2) { arr1.push(arr2[i]) } console.log("arr1:",arr1) console.log("arr2:",arr2)
结果如下:
方法二、arr1.push.apply(arr1,arr2)实现数组合并(比方法一好)
代码如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] arr1.push.apply(arr1,arr2) console.log("arr1:",arr1) console.log("arr2:",arr2)
结果如下:
方法三、concat方法合并俩数组生成新的数组
代码如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] arr1 = arr1.concat(arr2) console.log("concat方法") console.log("arr1:",arr1) console.log("arr2:",arr2)
结果如下:
方法四、ES6语法
代码如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] arr1 = [...arr1, ...arr2] console.log("ES6语法") console.log("arr1:",arr1) console.log("arr2:",arr2)
结果如下:
方法5、ES6语法+push方法
代码如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] arr1.push(...arr2) console.log("ES6语法+push方法") console.log("arr1:",arr1) console.log("arr2:",arr2)
结果如下:
二、数组去重
set方法去重
代码如下:
var arr = [1, 1, 2, 2, 2, 3, 3, 3] let res = Array.from(new Set(arr)) console.log(res)
结果如下:
参考文章:https://www.cnblogs.com/gaosirs/p/10677221.html
数组中是对象的去重方法:https://www.cnblogs.com/le220/p/9130656.html
代码记录:数组中存放为对象,根据对象中"dz"与“mzydmc”属性进行去重
let res = []; let obj = {}; for (let i = 0; i < arr.length; i++) { let dz = arr[i].dz let mzydmc = arr[i].mzydmc if (!obj[mzydmc]) { if (!obj[dz]){ res.push(arr[i]); obj[dz] = true } obj[mzydmc] = true }else { console.log(arr[i]) } }