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

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.过滤得到某数组中的多个字段放到一个数组里,查询多个组织id,人员id等;

方案1(push方法):
let ids = []
this.recordList.map(item => {
   ids.push(item.streetOrgIdList, item.community, item.addressOrgIds)
})
// 去掉所有假值,包括false/0,然后flat平铺数组
let effectIds = ids.filter(Boolean).flat()

方案2(flatMap方法):
let orgIds = []
// 定义所需字段
const fields = ['streetOrgIdList', 'community', 'addressOrgIds']
  orgIds = this.recordList.flatMap(item =>
    fields.map(field => item[field])
  )
let flatOrdIds = orgIds.filter(Boolean).flat()

---------------------------------
flat():当你在寻求展平嵌套数组而不改变元素时,flat() 是你的最佳选择。它可以将多层数组展平到你想要的深度,像藏宝图一样显示所有元素。
基础用法:
array.flat([depth])
array: 要展平的原始数组。
depth (可选): 指定展平的最大深度。默认值为 1
----------
flatMap():如果你的任务不仅是展平数组,而且还要先转换元素,例如在展平之前将每个元素映射到不同的值,那么 flatMap() 就是您值得信赖的伙伴。它结合了 map() 和 flat() 的功能,在一个英勇的行为中完成转换和展平。
基础用法:
array.flatMap(callback[, thisArg])
callback: 一个回调函数,它为每个元素调用并返回新的元素。
thisArg (可选): 执行回调时使用的 this 值。
const numbers = [1, 2, 3];
const doubledAndFlattened = numbers.flatMap(x => [x * 2]);
console.log(doubledAndFlattened); // 输出: [2, 4, 6]
--------
性能比较
flatMap() 更高效:使用 flatMap() 通常比先转换 map() 然后 flat() 更有效,因为 flatMap() 遍历数组一次,而不是两次。

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

const  combinedArray  =  array1.map(item  =>  {
          const  item2  =  array2.find(i  =>  i.noticeId  ===  item.dataId);
          return  {  ...item,  ...item2  };
});

2.根据某个相同属性值,给a数组赋值b数组的某一个字段值

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]
              }
            })
  1. every/some校验数组值是否符合条件(every-都符合条件,some-其中一个符合条件)
参数说明:
第一个参数为一个回调函数,必传,数组中的每一项都会遍历执行该函数。
currentValue:必传,当前项的值
index:选传,当前项的索引值
arr:选传,当前项所属的数组对象
第二个参数thisValue为可选参数,回调函数中的this会指向该参数对象。
let flag = array.every(function(currentValue,index,arr), thisValue)
用法举例:
let flag = resourceList.every((item) => {
    return item.supplier.name && item.resource.name
})

6.精确匹配数组对象中的多个值

const users = [
  { name: 'Alice', age: 28 },
  { name: 'Bob', age: 30 },
  { name: 'Carol', age: 22 },
  { name: 'David', age: 25 }
];

// 定义要精确匹配的年龄数组
const ageValues = [25, 28];

// 使用 filter 方法筛选出年龄为指定值的用户
const filteredUsers = users.filter(user => ageValues.includes(user.age));

console.log(filteredUsers);

//按顺序做精确匹配
let arr = [
  { appName: "党组织", moduleCode: 'dangzuzhi' },
  { appName: "党委", moduleCode: 'dangwei' },
  { appName: "党支部总数", moduleCode: 'dangzhibu' },
  { appName: "党总支", moduleCode: 'dangzongzhi' },
];
//自定义需要筛选出来的数据key和顺序
let newOrder = ['dangwei', 'dangzongzhi', 'dangzhibu', 'dangzuzhi'];
let newArr = newOrder.map(code => arr.find(item => item.moduleCode === code));

7.求和

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

8.多字段排序

       this.approveData = approveRes.sort(this.multiSort([
         ['approveStatus', 'desc'],
         ['updateTime', 'desc']
       ]));

 // 多字段排序
    multiSort(fields) {
      return (a, b) => {
        for (const [key, order = 'desc'] of fields) {
          const diff = a[key] - b[key];
          if (diff !== 0) {
            return order === 'desc' ? -diff : diff;
          }
        }
        return 0;
      }
    }

补充案例:
//排序approveStatus 非1排在前面(其余状态值平级) 再按updateTime降序
      this.approveData = [...approveRes].sort((a, b) => 
        (a.approveStatus === 1) - (b.approveStatus === 1) || b.updateTime - a.updateTime
      )
逻辑梳理:
[...approveRes]复制一份数据,不更改源数据
true - false = 1,false - true = -1;
所以:
a 是 1,b 不是 1 → 返回正值 → a 应该靠后;
a 不是 1,b 是 1 → 返回负值 → a 靠前;
如果两个都是 1 或都不是 1,那就进入 updateTime 排序。

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)
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容