對象數組去重及 array.reduce() 方法的記錄

對象數組去重(格式化)

前端拿到後端返回的數據後,每每要格式化以知足頁面需求。咱們能夠使用數組的 reduce() 方法對象數組(數組裏面存放的是對象)進行去重。前端

示例代碼以下:後端

let data = [
      { name: 'tom', id: 1 },
  	  { name: 'jack', id: 2 },
  	  { name: 'sam', id: 3 },
  	  { name: 'mike', id: 1 },
  	  { name: 'amy', id: 2 },
  	  { name: 'eric', id: 3 }
    ]
	
    let hash = {}
    data = data.reduce((item, next) => {
      // 根據 id 去重
      if(!hash[next.id]) {
        hash[next.id] = true
        item.push(next)
      }
      return item
    }, [])
	console.log(hash) // {1: true, 2: true, 3: true}
    console.log(data)

去重後結果以下所示:數組

reduce() 方法用法記錄

語法:函數

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
  • reduce() 方法接受兩個參數,第一個爲回調函數(必填),第二個爲初始值(非必填項)
  • callback() 執行數組中每一個值 (若是沒有提供 initialValue則第一個值除外)的函數
    • **accumulator: **累計器累計回調的返回值; 它是上一次調用回調時返回的累積值,或initialValue
    • currentValue: 數組中正在處理的元素
    • index (可選): 數組中正在處理的當前元素的索引。 若是提供了initialValue,則起始索引號爲0,不然從索引1起始。
    • array (可選): 調用reduce()的數組
  • initialValue 可選
    • 做爲第一次調用 callback函數時的第一個參數的值。 若是沒有提供初始值,則將使用數組中的第一個元素。 在沒有初始值的空數組上調用 reduce 將報錯。

callback() 回調函數中要有一個返回值.net

描述:code

回調函數第一次執行時,accumulatorcurrentValue 的取值有兩種狀況:對象

  • 若是調用 reduce() 時提供了初始值 initialValue ,那麼 accumulator 取值爲 initialValue(), currentValue取數組中的第一個值;
  • 若是沒有提供 initialValue,那麼accumulator取數組中的第一個值,currentValue取數組中的第二個值。

若是數組爲空且沒有提供initialValue,會拋出TypeError 。若是數組僅有一個元素(不管位置如何)而且沒有提供initialValue, 或者有提供initialValue可是數組爲空,那麼此惟一值將被返回而且callback不會被執行。blog

計算數組中每一個元素出現的次數索引

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

  var countedNames = names.reduce(function (allNames, name) { 
    if (name in allNames) {
      allNames[name]++;
    }
    else {
      allNames[name] = 1;
    }
    return allNames;
  }, {});
  // countedNames is:
  // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

數組去重ip

let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
   let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
       if (accumulator.indexOf(currentValue) === -1) {
         accumulator.push(currentValue)
       }
       return accumulator
   }, [])

   console.log(myOrderedArray) // ["a", "b", "c", "e", "d"]

參考文章:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://blog.csdn.net/alisa_lisa/article/details/100927226

相關文章
相關標籤/搜索