js对象数组合并、去重、删除部分元素(concat()、reduce()、filter()、every()方法的使用) 低版本浏览器不支持

需求1:将左边选中的某些设备添加到右边,已有的不重复添加。


两边都是对象数组,刚开始想的原始的2重for循环遍历,效率比较低。后来想到将左边选中一律合并到右边的数组中,然后对右边的数组去重。这里要用到两个方法:concat()reduce()

将一个数组合并到另一个数组中。如果使用push(),添加的是整个数组而不是数组的元素。如let a = ['a']; let b =[ 'b']。如果a.push(b)。得到的结果是a = ['a', ['b']],而不是a=['a', 'b']。要想得到期望的结果要用concat():a.concat(b)。

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

语法:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数

参数描述
function(total,currentValue, index,arr)必需。用于执行每个数组元素的函数。
函数参数:
参数描述
total必需。初始值, 或者计算结束后的返回值。
currentValue必需。当前元素
currentIndex可选。当前元素的索引
arr可选。当前元素所属的数组对象。
initialValue可选。传递给函数的初始值

此处用于根据deviceID去重:

  1. // 添加设备
  2. handleAddDevices () {
  3. this.adevices = this.adevices.concat(this.selectDevices)
  4. let hash = {}
  5. this.adevices = this.adevices.reduce((item, next) => {
  6. if (!hash[next.deviceID]) {
  7. hash[next.deviceID] = true
  8. item.push(next)
  9. }
  10. return item
  11. }, [])
  12. },


需求2:移除选中设备


实现代码如下:

  1. // 移除选中设备
  2. handleRemoveDevices () {
  3. this.adevices = this.adevices.filter(item => { return this.rDevices.every(data => data.deviceID !== item.deviceID) })
  4. },

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

array.filter(function(currentValue,index,arr), thisValue)

参数说明

参数描述
function(currentValue, index,arr)必须。函数,数组中的每个元素都会执行这个函数
函数参数:
参数描述
currentValue必须。当前元素的值
index可选。当前元素的索引值
arr可选。当前元素属于的数组对象
thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"

every() 方法用于检测数组所有元素是否都符合指定条件(通过函数提供)。

array.every(function(currentValue,index,arr), thisValue)

参数说明

参数描述
function(currentValue, index,arr)必须。函数,数组中的每个元素都会执行这个函数
函数参数:
参数描述
currentValue必须。当前元素的值
index可选。当前元素的索引值
arr可选。当前元素属于的数组对象
thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"

原文链接 https://blog.csdn.net/qingmengwuhen1/article/details/79876813

原文地址:https://www.cnblogs.com/sunny3158/p/12215460.html