常用数组处理方法与数组去重

后端传过来的那么多数据我们怎么处理

归类:

常见改变原数组的:

  • splice() 添加/删除
  • sort() 数组排序
  • pop()删除数组中的最后一个元素,返回这个元素
  • push() 向数组的末尾添加一个元素,返回数组长度
  • unshift() 向数组的开头添加一个或更多元素,并返回新的长度。
  • reverse() 颠倒数组中元素的顺序
  • fill() 填充数组
    常见不改变原数组的
  • slice() 截取数组
  • join() 数组转字符串
  • toString() 数组转字符串
  • cancat 拼接数组
  • indexOf() 查找数组是否存在某个元素,返回下标
  • includes() 查找数组是否包含某个元素 返回布尔
    数组常用遍历
  • forEach()
  • every() 检测数组所有元素是否都符合判断条件,返回布尔值
  • some() 数组中的是否有满足判断条件的元素
  • map() 对数组中的每个元素进行处理,返回新的数组
  • filter() 根据条件筛选数组
  • reduce() 为数组提供累加器,合并为一个值
  • find()& findIndex() 根据条件找到数组成员

1. 数组添加值

  • 利用数组的索引添加
let color = ["red", "blue", "green"]
// 数组中增加值
// color[1] = "yellow"
color[3] = "yellow"
console.log (color)//[ 'red', 'blue', 'green', 'yellow' ]
color[5] = "yellow"//[ 'red', 'blue', 'green', <2 empty items>, 'yellow' ]

2. 获取数组最后一个元素

let color = ["red", "blue", "green",'red', 'blue', 'green']
color[color.length-1]

3.将数组转换成字符串

*1. toString() (不改变原数组)

返回将数组转换成用数组值以逗号分割开的字符串

let color = ["red", "blue", "green"]
color.toString()
let color = ["red", "blue", "green"]
let _color = color.toString()
console.log (color)//[ 'red', 'blue', 'green' ]
console.log (_color)//"red,blue,green"

根据打印结果可以看出来toString方法不会改变原数组,arrayObject 的字符串表示
*2. join()

返回一个自定义分隔符的以数组元素组成的字符串,不传值默认是以","分隔

let color = ["red", "blue", "green"]
console.log (color.join( ))//red,blue,green
console.log (color.join(":"))//red:blue:green

4.数组添加元素

  1. unshift() (改变)

在数组的开头添加元素,根据答应结果可以看出,unshift()改变了原数组,返回值是改变后数组的长度

let color = ['a', 'b', 'c']
console.log(color.unshift('w')) //4
console.log(color)//[ 'w', 'a', 'b', 'c' ]
  1. push()

在数组的结尾添加元素,根据打印结果可以看出,push()方法改变了原数组,返回值是改变后数组的长度

let color = ['a', 'b', 'c']

console.log(color.push('w'))//4
console.log (color)//[ 'a', 'b', 'c', 'w' ]

5. 数组删除元素

  1. pop()(改变)

删除数组中最后一个元素改变了原数组,返回的是删除的元素

let color = ['a', 'b', 'c']
console.log(color.pop())//'c'
console.log(color)//['a,'b']
  1. shift()(改变)

删除数组中首个元素,并把所有其他元素移到更低的索引,改变了原数组,返回的是删除的元素

  let color = ['a', 'b', 'c']
  console.log (color.shift())//'a'
  console.log (color)//[ 'b', 'c' ]

5. 修改数组

  1. splice(index,howmany,item1,…,itemX) 方法向/从数组中添加/删除项目,

改变了原数组,返回被删除的项目。
index:整数,规定添加/删除项目的位置
howmany:要删除的项目数量。如果设置为 0,则不会删除项目
可选。向数组添加的新项目。

/*删除数组*/
let color = ['a', 'b', 'c']
console.log(color.splice(1,1))//['b']
console.log(color)//[ 'a', 'c' ]
/*增加数组*/
let _color = ['a', 'b', 'c']
console.log(_color.splice(1,0,'pz'))//[],没有删除元素所以为空
console.log(_color)//[ 'a', 'pz', 'b', 'c' ]
  1. slice(start,end)“截取”

不改变原数组,返回一个新的数组,包含从 start 到 end (不包括该元素)的 原数组中的元素。
start 规定从何处开始选取。如果是负数,那么它规定从数组尾部开始算起的位置。也就是说,-1 指最后一个元素,-2 指倒数第二个元素,以此类推。
end 可选。规定从何处结束选取。该参数是数组片断结束处的数组下标。如果没有指定该参数,那么切分的数组包含从 start 到数组结束的所有元素。如果这个参数是负数,那么它规定的是从数组尾部开始算起的元素。

let color = ['a', 'b', 'c']
console.log(color.slice( -3,-1))//[ 'a', 'b' ]
console.log(color)//[ 'a', 'b', 'c' ]

let color = ['a', 'b', 'c']
console.log(color.slice( 1,2))//[ 'b' ]
console.log(color)//[ 'a', 'b', 'c' ]
  1. concat()方法用于连接两个或多个数组

不会改变原数组
返回拼接的数组

let man = ['a', 'b']
let woman = ['b', 'd']
let child = man.concat(woman)
console.log(child)//[ 'a', 'b', 'b', 'd' ]

6.数组循环遍历

  1. foEach 为数组中的每个元素执行一次回调函数。回调函数的参数,数组当前项的值,数组当前项的索引,数组对象本身,不会改变原数组,返回值是undefined
let arr = ['a', 'b', 'c']
arr.forEach((item,index) => {
  console.log (item,index)
} )
console.log (arr)

  1. map 返回一个由回调函数的返回值组成的新数组。不会改变原数组,回调函数传递三个参数(数组中正在处理的当前元素,数组中正在处理的当前元素的索引)
 let arr = [1, 2, 3] 
let _arr = arr.map((item,index) =>item*2)
console.log(arr) //[ 1, 2, 3 ]
console.log(_arr)//[ 2, 4, 6 ]

  1. every 如果数组中的每个元素都满足测试函数,则返回 true,否则返回 false。(与some重点对比),不会改变原数组
let arr = [1, 2, 3] 
console.log(arr.every((item,index) => item > 2))//false
  1. some 如果数组中至少有一个元素满足测试函数,则返回 true,否则返回 false。不会改变原数组
let arr = [1, 2, 3] 
console.log(arr.some((item,index) => item > 2))//true
  1. for…of循环:keys/value/entries
  • values() 方法返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值
  • entries() 方法返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。
  • keys() 方法返回一个包含数组中每个索引键的Array Iterator对象
let arr=['a','b','c']

for (let item of arr){
    console.log(item);
}
 var arr = ["abc", "bcd", "234", , , , 54, 2, 1];
        for (var key of arr.keys()) {
            console.log (key)//0,1,2,3,4,5,6,7,8
        }
        for (var value of arr.values()){
            console.log(value)//abc bcd 234 undefined undefined undefined 54 2 1
        }
        for (var entry of arr.entries()){
            console.log(entry)
        }
// [ 0, 'abc' ]
// [ 1, 'bcd' ]
// [ 2, '234' ]
// [ 3, undefined ]
// [ 4, undefined ]
// [ 5, undefined ]
// [ 6, 54 ]
// [ 7, 2 ]
// [ 8, 1 ]
  1. filter 将所有在过滤函数中返回 true 的数组元素放进一个新数组中并返回。不会改变原数组
let name = ['pz', 'yjl','kobe','James']
let _name = name.filter((item,index)=> item.length > 3)
console.log(name)//[ 'pz', 'yjl', 'kobe', 'James' ]
console.log(_name)//[ 'kobe', 'James' ]
  1. find 找到第一个满足测试函数的元素并返回那个元素的值,如果找不到,则返回 undefined。不会改变原数组
let name = ['pz', 'yjl','kobe','James']
let _name = name.find((item,index)=> item.length > 3)
let _name2 = name.find((item,index)=> item.length > 5)
console.log(name)//[ 'pz', 'yjl', 'kobe', 'James' ]
console.log(_name)//kobe
console.log(_name2)//undefined

7. 转换数据格式

  1. of() 它负责把一堆文本或者变量转换成数组,方法创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型
let arr =Array.of(3,4,5,6);
console.log(arr);//[ 3, 4, 5, 6 ]
let arr =Array.of('pz', 'yjl','kobe','James');
console.log(arr);//[ 'pz', 'yjl', 'kobe', 'James' ]
  1. from 法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例,JSON数组格式转换成数组,JSON的数组格式就是为了前端快速的把JSON转换成数组的一种格式,
let  json = {
    '0': 'a',
    '1': 'bb',
    '2': 'ccc',
    length:3
}
let arr=Array.from(json);
console.log(arr)//[ 'a', 'bb', 'ccc' ]

console.log(Array.from([1, 2, 3], x => x + x));

数组去重 ***

数组去重在工作中真的是很常见的业务处理,那么总结一下常用方法义不容辞,实际上有两种业务情况,第一种是在一个数组中有重复项,需要去除重复项,另一种是对比另一个数组,去掉跟另一个数组重复的项

一.在一个数组中有重复项

1.运用Set数据结构和from(ES6常用方法)

前置知识:Set本身是一个构造函数,用来生成Set数据结构,ES6提供了新的数据结构Set,类似于数组,但是成员的值都是唯一的,没有重复的值。

eg1:
const set = new Set()
const arr = [1, 2, 3,3, 4, 4, 5]
arr.forEach(x => set.add(x))
console.log(set)//Set { 1, 2, 3, 4, 5 }
for(let item of set) {
  console.log(item)// 1, 2, 3, 4, 5
}
//eg2:Set+扩展运算符(...)数组去重
const set2 = new Set([1, 2, 3,3, 4, 4, 5])
console.log([...set2])//[ 1, 2, 3, 4, 5 ]

封装数组去重方法

const unique = arr => Array.from(new Set(arr))//封装函数
const arr = [1, 2, 3,3, 4, 4, 5]
let uniqueArr = unique(arr)//代用
console.log(uniqueArr)//[ 1, 2, 3, 4, 5 ]

这个是代码量最少的方法

2. for循环+splice (三种写法)

/*循环的元素的后面有没有跟该元素相同的*/
const unique = arr => {
  for (let i = 0; i < arr.length; i++) {
    for(let j = i+1; j < arr.length-1; j++) {
      if (arr[i]===arr[j]) {
        arr.splice(i,1)
        i--
      }
    }
  }
  return arr
}
/*另一种写法,循环的元素的前面有没有跟该元素相同的*/
const unique = arr => {
  for (let i = 0; i < arr.length; i++) {
    for(let j = 0; j < i; j++) {
      if (arr[i]===arr[j]) {
        arr.splice(i,1)
        i--
      }
    }
  }
  return arr
}
/*不改变原始数组的方法*/
const unique = (arr,uniqueArr )=> {
  for (let i = 0; i < arr.length; i++) {
    for(let j = i+1; j < arr.length; j++) {
      if (arr[i]===arr[j]) {
        j=++i
      }
    }
    uniqueArr.push(arr[i])
  }

}
const arr = [1, 2, 3, 3, 4, 4, 5]
let uniqueArr= new Array()
unique(arr,uniqueArr)
console.log(uniqueArr)

3. indexof()+for循环 不改边原数组

const unique = (arr,uniqueArr )=> {
  if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
  for (let i = 0; i < arr.length; i++) {
    uniqueArr.indexOf (arr[i]) === -1 && uniqueArr.push(arr[i])
  }
}
const arr = [1, 2, 3, 3, 4, 4, 5]
let uniqueArr= new Array()
unique(arr,uniqueArr)
console.log(uniqueArr)

4.filter() +indexOf()

const unique = arr => arr.filter((item,index) => arr.indexOf(item)===index) 
const arr = [1, 2, 3, 3, 4, 4, 5]
let uniqueArr= unique(arr)
console.log(uniqueArr)

5.用对象的属性不能相同的特点减少循环次数(速度快)

const unique = (arr,uniqueArr )=> {
  if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
  let tag = {}
  for (let i = 0; i < arr.length; i++) {
    if(!tag[arr[i]]) {
      uniqueArr.push(arr[i])
      tag[arr[i]]=true
    }

  }
}
const arr = [1, 2, 3, 3, 4, 4, 5]
let uniqueArr= new Array()
unique(arr,uniqueArr)
console.log(uniqueArr)

二.去除两个数组中相同的项(工作常遇到)

主要用filter过滤数组

const a=[1,2,3,4,5]
const b=[2,3,7,8,9]
console.log(a.filter(item=>b.indexOf(item)===-1))
console.log(a.filter(item =>!b.some(e => e === item)))
console.log(a.filter(v => !b.includes(v)))
console.log(a.filter(item => b.every(e => e!== item)))

tip:>(免费获取最新完整前端课程关注vx公众号:前端拓路者coder,回复:资料
如果这个文章对你有用的话,欢迎点赞转发关注,让更多的小伙伴看到呀,毕竟分享是一个程序员最基本的美德!!!如果有不对的请大佬指教)

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值