常用數組處理方法與數組去重

後端傳過來的那麼多數據我們怎麼處理

歸類:

常見改變原數組的:

  • 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,回覆:資料
如果這個文章對你有用的話,歡迎點贊轉發關注,讓更多的小夥伴看到呀,畢竟分享是一個程序員最基本的美德!!!如果有不對的請大佬指教)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章