Skip to content

数组对象去重算法

93 字小于 1 分钟

算法

2024-12-29

function getOnlyData(data, field) {
      let result = []
      const suggestionMap = {}
      const length = data.length
      if (length === 0) {
        return result
      }
      for (let i = 0; i < length; i++) {
        let currentItem = data[i]
        let suggestion = currentItem[field]
        if (!suggestionMap[suggestion]) {
          suggestionMap[suggestion] = true
          result.push(currentItem)
        }
      }
      return result
    }
let data = [{name:'张三',value:'1'},{name:'张三',value:'2'},{name:'李四',value:'3'}]
getOnlyData(data,'name')

/* [
    {
        "name": "张三",
        "value": "1"
    },
    {
        "name": "李四",
        "value": "3"
    }
]*/