一些常用的数组方法案例(持续更新)

https://www.wangt.cc/2021/01/%E6%95%B0%E7%BB%84%E5%B9%B6%E9%9B%86-%E4%BA%A4%E9%9B%86-%E5%B7%AE%E9%9B%86/

1.筛选需要的数组数据;

this.arr.filter(item => item.channel==3 || item.channel==6)

2.根据某个相同属性值,组合两个数组

a.map(el=>{el.label=b.find(item=>item.channel==el.channel).label})
  1. 根据A数组的key筛选出B数组里对应的数据
let checkList = ['110101202210242255', '612524196710250612']
this.familyList = [
  { 
    idcard: '110101202210242255',
    name: '张三'
  },
  { 
    idcard: '612524196710250612',
    name: '李四'
  },
  { 
    idcard: '612524196710250699',
    name: '王五'
  },
]
// 方法1:
let newList = this.familyList.filter(el => {
    return checkList.some(curVal => curVal === el.idcard)
})
// 方法2:
let newList = this.familyList.filter(el => {
    return checkList.find(item => {
         return el.idcard == item
    })
})
// 筛选非A数组的key的其它项:
let newList = this.familyList.filter(el => {
    return !checkList.find(item => {
         return el.idcard == item
    })
})

4.将两个数组组装成对象数组

needArr = joinIds.map((i,index)=>{
          return {
                id: i,
                name: joinNames[index]
              }
            })

5.求和

let total = data.reduce((t, v) => {
                return t + v.value
            }, 0)

ES5

var a = [1,2,3];
var b = [1,2,2,4];
//并集(去重)
var union = a.concat(b.filter(function(v) {return a.indexOf(v) === -1 } )); // [1,2,3,4]
//交集
var intersection = a.filter(function(v){ return b.indexOf(v) > -1 }); // [1,2]
//差集
var difference = a.filter(function(v){ return b.indexOf(v) === -1 }); // [3]

ES6

let a = [1,2,3];
let b = [1,2,2,4];
let aSet = new Set(a);
let bSet = new Set(b);
//并集(去重)
let union = Array.from(new Set(a.concat(b))); // [1,2,3,4]
//交集
let intersection = Array.from(new Set(a.filter(v => bSet.has(v)))); // [2]
//差集
let differenceNew = Array.from(new Set(a.concat(b).filter(v => aSet.has(v) && !bSet.has(v))); // [3]

ES7

let a = [1,2,3];
let b = [1,2,2,4];
//并集(去重)
let union = a.concat(b.filter(v => !a.includes(v))); // [1,2,3,4]
//交集
let intersection = a.filter(v => b.includes(v)); // [1,2]
//差集
let difference = a.concat(b).filter(v => a.includes(v) && !b.includes(v)); // [3]

数组遍历延迟执行

    for (let i = 0; i < fileIds.length; i++) {
      setTimeout(() => {
        let params = {
          fileId: fileIds[i],
          page: { page: 1, pageSize: 999 }
        }
      //每三秒用遍历的item请求一次接口
        service.queryFileOrNoticeReadInfoList(params).then(res => {
          res.data.map(item=>{
            if (item.memberId == memberId && item.readStatus == true)
            readedFileIds.push(item.fileId)
          })
        }).catch(error => {
          reject(error)
        })
        if (i >= fileIds.length -1) {
          let totalReadIds = [...localReadIds, ...readedFileIds]
          // 缓存已读ids
          localStorage.setItem('readedFileIds', JSON.stringify(totalReadIds))
          resolve(totalReadIds)
        }
      }, 3000 * i)
    }

你可能感兴趣的:(一些常用的数组方法案例(持续更新))