数组方法

187 阅读10分钟
  • 数组排序

    // 对数字进行排序,简写
    const arr = [3, 2, 4, 1, 5]
    arr.sort((a, b) => a - b)
    console.log(arr) // [1, 2, 3, 4, 5]
    
    // 对字母进行排序,简写
    const arr = ['b', 'c', 'a', 'e', 'd']
    arr.sort()
    console.log(arr) // ['a', 'b', 'c', 'd', 'e']
    
    

    冒泡排序

    function bubbleSort(arr) { let len = arr.length for (let i = 0; i < len - 1; i++) { // 从第一个元素开始,比较相邻的两个元素,前者大就交换位置 for (let j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { let num = arr[j] arr[j] = arr[j + 1] arr[j + 1] = num } } // 每次遍历结束,都能找到一个最大值,放在数组最后 } return arr }

    //测试 console.log(bubbleSort([2, 3, 1, 5, 4])) // [1, 2, 3, 4, 5]

  • 数组去重

    Set 去重

    cosnt newArr = [...new Set(arr)] 
    
    
    

    Array.from 去重

    const newArr = Array.from(new Set(arr))
    

    indexOf 去重

    function resetArr(arr) {
      let res = []
      arr.forEach(item => {
        if (res.indexOf(item) === -1) {
          res.push(item)
        }
      })
      return res
    }
    
    // 测试
    const arr = [1, 1, 2, 3, 3]
    console.log(resetArr(arr)) // [1, 2, 3]
    
  • 数组并集

    const union = function (a, b, k) { return a.concat(b.filter(i => (k ? !a.map(i => i[k]).includes(i[k]) : !a.includes(i)))) } 复制代码

示例:

let a = [1, 2, 3, 4, 5]
let b = [1, 2, 4, 5, 6]
union(a, b) //[1,2,3,4,5,6]

// 场景2:
let a1 = [
    { id: 1, name: '张三', age: 20 },
    { id: 2, name: '李四', age: 21 },
    { id: 3, name: '小二', age: 23 }
]
let b1 = [
    { id: 2, name: '李四', age: 21 },
    { id: 4, name: '小明', age: 24 },
    { id: 5, name: '小红', age: 25 }
]

// 通过 id 获取并集
union(a1, b1, 'id')
/*
[
  {id: 1, name: "张三", age: 20}
  {id: 2, name: "李四", age: 21}
  {id: 3, name: "小二", age: 23}
  {id: 4, name: "小明", age: 24}
  {id: 5, name: "小红", age: 25}
]
*/
复制代码
  • 数组交集

    const intersection = function (a, b, k) { return a.filter(t => (k ? b.map(i => i[k]).includes(t[k]) : b.includes(t))) } 复制代码

示例:

let a = [1, 2, 3, 4, 5]
let b = [1, 2, 4, 5, 6]
intersection(a, b) // [1,2,4,5]

// 场景2:
let a1 = [
    { id: 1, name: '张三', age: 20 },
    { id: 2, name: '李四', age: 21 },
    { id: 3, name: '小二', age: 23 }
]
let b1 = [
    { id: 2, name: '李四', age: 21 },
    { id: 4, name: '小明', age: 24 },
    { id: 5, name: '小红', age: 25 }
]
intersection(a1, b1, 'id') //[ { id: 2, name: '李四', age: 21 }]
复制代码
  • 数组差集

    const except = function (a, b, k) { return [...a, ...b].filter(i => ![a, b].every(t => (k ? t.map(i => i[k]).includes(i[k]) : t.includes(i)))) } 复制代码

示例:

let a = [1, 2, 3, 4, 5]
let b = [1, 2, 4, 5, 6]

except(a, b) // [3,6]

let a1 = [
    { id: 1, name: '张三', age: 20 },
    { id: 2, name: '李四', age: 21 },
    { id: 3, name: '小二', age: 23 }
]
let b1 = [
    { id: 2, name: '李四', age: 21 },
    { id: 4, name: '小明', age: 24 },
    { id: 5, name: '小红', age: 25 }
]


except(a1, b1, 'id')
/*
[
  {id: 1, name: "张三", age: 20}
  {id: 3, name: "小二", age: 23}
  {id: 4, name: "小明", age: 24}
  {id: 5, name: "小红", age: 25}
]
*/
复制代码
  • 数组分组

    /**

    • @description: 一维数组转二维数组 (分组)
    • @param {Array} arr:数组
    • @param {Number} num: 平分基数(num 个为一组进行分组(归档)) */ const group = function (arr, num) { return [...Array(Math.ceil(arr.length / num)).keys()].reduce((p, _, i) => (p.push(arr.slice(i * num, (i + 1) * num)), p), []) } 复制代码

示例:

  group([1,2,3,4,5,6,7,8,9,10],2) // [[1,2],[3,4],[5,6],[7,8],[9.10]]
 
  group([1,2,3,4,5,6,7,8,9,10],3) // [[1,2,3],[4,5,6],[7,8,9],[10]]
复制代码
  • 数组平均数

    /**

    • 数组平均数
    • @param {Array} a:数组
    • @param {Function | String} f:函数 或 key */ const mean = function (a, f) { return (f ? a.map(typeof f === 'function' ? f : v => v[f]) : a).reduce((acc, val) => acc + val * 1, 0) / a.length } 复制代码

示例:

  mean([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n) // 5
  mean([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n') // 5
  mean([4, 2, 8, 6]) // 5
  mean(['4', 2, '8', 6]) // 5
复制代码
  • 数组生成

    /**

    • @description: 生成 起止数字间(包含起止数字)的升序数组
    • @param {Number} min : 最小值
    • @param {Number} max :最大值 */ const range = function (min, max) { return Array.from({ length: max - min + 1 }, (_, i) => i + min) } 复制代码

示例:

 range(0,10) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 range(1,9)  // [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
复制代码
  • 数组求和

    const sum = function (a, k) { return a.reduce((p, c) => p + (k ? c[k] || 0 : c), 0) } 复制代码

示例:

let a = [1, 2, 3, 4, 5]
sum(a) // 15

let a1 = [
    { id: 1, name: '张三', age: 20 },
    { id: 2, name: '李四', age: 21 },
    { id: 3, name: '小二', age: 23 }
]
sum(a1, 'age') // 64 
  • 数组值位置交换

    /**

    • @description: 交换数组中任一两个值的位置
    • @param {Array} arr:数组
    • @param {Number} oldIndex:老位置索引
    • @param {Number} newIndex:新位置索引
    • @param {Boolean} isChangeOldArr: 是否改变原数组
    • @return {Array} 返回一个数组 */ const exchangePostion = function (arr, oldIndex, newIndex, isChangeOldArr = false) { let a = isChangeOldArr ? arr : JSON.parse(JSON.stringify(arr)) a.splice(oldIndex, 1, a.splice(newIndex, 1, a[oldIndex])[0]) return a } 复制代码

示例:

 let a1 = [1, 2, 3, 4, 5, 6]
 
 exchangePostion(a1, 4, 1)// [1, 5, 3, 4, 2, 6]
 
 a1 //[1, 2, 3, 4, 5, 6]
 
 let a1 = [1, 2, 3, 4, 5, 6]
 
 exchangePostion(a1, 4, 1,true)// [1, 5, 3, 4, 2, 6]
 
  a1 // [1, 5, 3, 4, 2, 6]
复制代码

数组的添加

数组的首位添加

unshift

let arr = [1,2,3,4,5]

//在数组arr首位插入9,10两个值
arr.unshift(9,10)

arr // [9,10,1,2,3,4,5]
复制代码

splice

let arr = [1,2,3,4,5]

//在数组arr首位插入9,10两个值
arr.splice(0,0,9,10)

arr // [9,10,1,2,3,4,5]
复制代码

数组的末位添加

push

let arr = [1,2,3,4,5]

//在数组arr末尾添加一个6
arr.push(6)

arr // [1, 2, 3, 4, 5, 6]
复制代码

splice

let arr = [1,2,3,4,5]

//在数组arr末尾添加一个6
arr.splice(arr.length,0,6)

arr // [1, 2, 3, 4, 5, 6]
复制代码

数组的中间添加

splice

let arr = [1,2,3,4,5]

//在数组arr索引为1的值前面插入9,10两个值
lis.splice(1,0,9,10) 

lis // [1, 9, 10, 2, 3, 4, 5]
复制代码

数组的删除

数组首位删除

shift

let arr = [1,2,3,4,5]
arr.shift()
arr              //[2,3,4,5]
复制代码

splice

let arr = [1,2,3,4,5]
arr.splice(0,1)
arr             //[2,3,4,5]
复制代码

数组末位删除

pop

let arr = [1,2,3,4,5]
arr.pop()                   
arr                          //[1,2,3,4]
复制代码

splice

let arr = [1,2,3,4,5]
arr.splice(arr1.length-1,1)
arr                         //[1,2,3,4]
复制代码

数组中间删除

splice

let arr = [1,2,3,4,5]

//从数组索引 为 1 的开始,删除 1 个
arr.splice(1,1)
arr //[1,3,4,5]

let arr1 = [1,2,3,4,5]

//从数组索引 为 1 的开始,删除 2 个
arr1.splice(1,2)
arr1 //[1,4,5]
复制代码

数组的替换

数组的首位替换

splice

let arr = [1,2,3,4,5]

//在数组arr首位(1) 替换成 8和9
arr.splice(0,1,8,9)

arr //[8, 9, 2, 3, 4, 5]
复制代码

数组的末位替换

splice

let arr = [1,2,3,4,5]

//在数组arr末位 (5) 替换成 8和9
arr.splice(arr.length-1,1,8,9)

arr //[1,2,3,4,8,9]
复制代码

数组的中间替换

splice

let lis1 = [1,2,3,4,5]

//删除了lis数组中索引为 3 的值(4),同时用9和10替换了其位置
lis1.splice(3,1,9,10)

lis1 // [1,2,3,9,10,5]
复制代码

数组的查询

数组中值的查询

查询数组中符合给定条件的第一个值

find

let jsonArr = [
  {id:'1',name:'lisi',age:30},
  {id:'2',name:'zhangsan',age:20},
  {id:'3',name:'lisi',age:30}
]
//找到 age 为 30的值
jsonArr.find(item=>item.age===30)  //{id: "1", name: "lisi", age: 30}
//找到 age为 301的值
jsonArr.find(item=>item.age===301) //undefined
复制代码

倒序查询数组中符合给定条件的第一个值

lastFind (自定义方法)

function lastFind(jsonArr,callback){
    let _jsonArr = jsonArr.reverse()
    let obj = _jsonArr.find(callback)
    return obj
}
let jsonArr = [
  {id:'1',name:'lisi',age:30},
  {id:'2',name:'zhangsan',age:20},
  {id:'3',name:'wangermazi',age:30},
  {id:'4',name:'xiaoming',age:18},
  {id:'5',name:'wuming',age:30},
]
lastFind(jsonArr,item=>item.age==30) //  {id: "5", name: "wuming", age: 30}
lastFind(jsonArr,item=>item.age==18) //  {id: "4", name: "xiaoming", age: 18}
lastFind(jsonArr,item=>item.age==188)//  undefined
复制代码

查询数组中符合给定条件的所有值

filter

let jsonArr = [
  {id:'1',name:'lisi',age:30},
  {id:'2',name:'zhangsan',age:20},
  {id:'3',name:'lisi',age:30}
]
//找到 age 为 30的所有值
jsonArr.filter(item=>item.age===30) //[{id:'1',name:'lisi',age:30},{id:'3',name:'lisi',age:30}]
//找到 age为 301的所有值
jsonArr.filter(item=>item.age===301) //[]
复制代码

数组中值索引的查询

查询数组中符合给定条件的第一个值的索引

findIndex

let jsonArr = [
  {id:'1',name:'lisi',age:30},
  {id:'2',name:'zhangsan',age:20},
  {id:'3',name:'lisi',age:30}
]
// 查询age为30的第一个值的索引
jsonArr.findIndex(item=>item.age===30)//0
复制代码

indexOf(普通值)

let arr = [1,2,1,4]
arr.indexOf(1)//0
复制代码

倒序查询数组中符合给定条件的第一个值的索引

lastFindIndex(自定义方法)

function lastFindIndex(jsonArr,callback){
    let _jsonArr = jsonArr.reverse()
    let index = _jsonArr.findIndex(callback)
    return index>-1?_jsonArr.length-index-1:-1
}
let jsonArr = [  {id:'1',name:'lisi',age:30},  {id:'2',name:'zhangsan',age:20},  {id:'3',name:'wangermazi',age:30},  {id:'4',name:'xiaoming',age:18},  {id:'5',name:'wuming',age:30},]

lastFindIndex(jsonArr,item=>item.age==18) //3
lastFindIndex(jsonArr,item=>item.age==30) //4
复制代码

lastIndexOf(普通值)

let arr = [1,2,1,4]
arr.lastIndexOf(1)//2
复制代码

倒序查询数组中符合给定条件的所有值的索引

allFindIndex (自定义方法)

function allFindIndex(jsonArr,callback){
    let res= []
    for(let i=0;i<jsonArr.length;i++){
        if(callback(jsonArr[i])){
            res.push(i)
        }
    }
    return res
}

let jsonArr = [  {id:'1',name:'lisi',age:30},  {id:'2',name:'zhangsan',age:20},  {id:'3',name:'wangermazi',age:30},  {id:'4',name:'xiaoming',age:18},  {id:'5',name:'wuming',age:30},]
//从jsonArr数组中  找到符合给定条件的值的所有索引

allFindIndex(jsonArr,item=>item.age==30)//  [0, 2, 4]
allFindIndex(jsonArr,item=>item.age==18)//  [3]
allFindIndex(jsonArr,item=>item.age==20)//  [1]
allFindIndex(jsonArr,item=>item.age==201)// []
复制代码

数组的判断

数组中的所有值是否都满足给定条件

every

let arr = [1,2,3,4,5]
//检测数组的每一项是否都大于0
arr.every(item=>item>0) //true

//检测数组的每一项是否都大于1
arr.every(item=>item>1) //false

//用户列表
let userList = [
  {id:'1',name:'lisi',age:30},
  {id:'2',name:'zhangsan',age:20},
  {id:'3',name:'wangermazi',age:30},
  {id:'4',name:'xiaoming',age:18},
  {id:'5',name:'wuming',age:30},
]
//未成年检测
userList.every(item=>item.age>=18)//true
复制代码

数组中是否包含满足给定条件的值

includes(普通值)

let arr = [1,2,3,4,5]
//检测数组中是否包含 4
arr.includes(4) //true
arr.includes(6) //false
复制代码

find(针对json数组

//用户列表
let userList = [
  {id:'1',name:'lisi',age:30},
  {id:'2',name:'zhangsan',age:20},
  {id:'3',name:'wangermazi',age:30},
  {id:'4',name:'xiaoming',age:18},
  {id:'5',name:'wuming',age:30},
]
//用户列表中是否包含年龄20岁的
!!userList.find(item=>item.age===20) // true
//用户列表中是否包含年龄201岁的
!!userList.find(item=>item.age===201)// false
复制代码

some(针对json数组):black_flag:推荐

//用户列表
let userList = [
  {id:'1',name:'lisi',age:30},
  {id:'2',name:'zhangsan',age:20},
  {id:'3',name:'wangermazi',age:30},
  {id:'4',name:'xiaoming',age:18},
  {id:'5',name:'wuming',age:30},
]
//用户列表中是否包含年龄20岁的
userList.some(item=>item.age===20) // true
//用户列表中是否包含年龄201岁的
userList.some(item=>item.age===201)// false
复制代码

数组的加工

数组整体加工

数组值拼接

join

let arr = [1,2,3,4,5]
arr.join('') //'12345'
复制代码

reduce

let arr = [1,2,3,4,5]
arr.reduce((pre,cur)=>pre+=cur,'') //'12345'
复制代码

数组合并

扩展运算符...

let arr11 = [1,2,3]
let arr22 = [4,5,6]
let arr33 = [7,8,9]
let res = [...arr11,...arr22,...arr33]
res //[1, 2, 3, 4, 5, 6, 7, 8, 9]
复制代码

concat

let arr11 = [1,2,3]
let arr22 = [4,5,6]
let arr33 = [7,8,9]
let res = arr11.concat(arr22,arr33)
res //[1, 2, 3, 4, 5, 6, 7, 8, 9]
复制代码

push

let res = [1,2,3]
let arr11 = [4,5,6]
let arr22 = [7,8,9]
res.push(...arr11,...arr22)
res //[1, 2, 3, 4, 5, 6, 7, 8, 9]
复制代码

数组值加工

reduce

let list = [1,2,3,4,5] // => ["1%", "2%", "3%", "4%", "5%"]

//数组值加工输出
list.reduce((pre,cur)=>pre.push(cur+'%')&&pre,[])//["1%", "2%", "3%", "4%", "5%"]
复制代码

**reduceRight **

let list = [1,2,3,4,5] // => ["1%", "2%", "3%", "4%", "5%"]

//数组值加工输出
list.reduceRight ((pre,cur)=>pre.push(cur+'%')&&pre,[])//["5%", "4%", "3%", "2%", "1%"]
复制代码

reduceRight 和 reduce相比顺序相反

map

let list = [1,2,3,4,5] // => ["1%", "2%", "3%", "4%", "5%"]

list.map(item=>item +='%') //["1%", "2%", "3%", "4%", "5%"]

//自定义返回的每一项的值 为 [] json数组值加工 优先考虑map
list.map(item=>[]) //[[],[],[],[],[]]
复制代码

可以自定义返回的每一项 map回调参数有3个,item(每一项)、index(每一项对应的索引)、arr(遍历的数组)

数组排序

数组倒序

reverse

let arr = [9,7,4,5,6,11]
arr.reverse()// [11, 6, 5, 4, 7, 9]
arr// [11, 6, 5, 4, 7, 9]
复制代码

数组按条件排序

sort

let arr = [9,7,4,5,6,11]

arr.sort((pre,next)=>pre-next) // [4, 5, 6, 7, 9, 11]
复制代码

数组的遍历

forEach

let arr2 = [4,5,6]

arr2.forEach((item,index,arr)=>{
 console.log(`当前项:${item},对应的索引是:${index},遍历的数组:${JSON.stringify(arr)}`)
})

//当前项:4,对应的索引是:0,遍历的数组是:[4,5,6]
//当前项:5,对应的索引是:1,遍历的数组是:[4,5,6]
//当前项:6,对应的索引是:2,遍历的数组是:[4,5,6]
复制代码

数组自身的遍历方法:forEach

for

let arr2 = [4,5,6]

for(let i=0;i<arr2.length;i++){
 console.log(`当前项:${arr2[i]},对应的索引是:${i},遍历的数组是:${JSON.stringify(arr2)}`)
}
//当前项:4,对应的索引是:0,遍历的数组是:[4,5,6]
//当前项:5,对应的索引是:1,遍历的数组是:[4,5,6]
//当前项:6,对应的索引是:2,遍历的数组是:[4,5,6]
复制代码

数组类型判断

isArray

let arr = []
let str= ''
Array.isArray(arr)//true
Array.isArray(str)//false
复制代码

数组的浅拷贝

slice

let lis = [1,2,3,4,5]
let cloneLis = lis.slice()

lis.push(6)

lis      //[1, 2, 3, 4, 5, 6]
cloneLis //[1,2,3,4,5]
复制代码

concat

let lis = [1,2,3,4,5]
let cloneLis = [].concat(lis)

lis.push(6) 

lis      //[1, 2, 3, 4, 5, 6]
cloneLis //[1,2,3,4,5]
复制代码

数组的深拷贝

JSON.parse(JSON.stringify( ))

let lis = [{a:1},{a:2}]
let cloneLis = JSON.parse(JSON.stringify(lis))

lis[0].a=10
lis      //[{a:10},{a:2}]
cloneLis //[{a:1},{a:2}]
复制代码

缺点:如果对象里有正则,直接把 正则 解析成 { },时间 转换成 字符串等