跳至主要內容

数组常见业务操作场景

zfh大约 2 分钟约 669 字...

对象数组根据数据项状态属性筛选数据

vue中往往使用计算属性去完成,这里使用数组三种不同的方法完成:

// 统计当前已完成的数据项
    doneSum() {
      // ``````reduce`````
      return this.todos.reduce((acc, cur) => {
        return acc + (cur.done ? 1 : 0);
      }, 0);
      // ``````filter`````
      const done  = this.todos.filter((todo)=>{
        return todo.done==true
      })
      return done.length
      // ````forEach`````
        let i =0
        this.todos.forEach(element => {
            if(element.done==true){
              i++
            }
        })
        return i
    },

数组对象根据对象中指定的属性去重

只有对象重复排重比较符合实际业务,毕竟后端的数据都是数组对象,业务很可能会出现根据 ID 来排重,纯数组去重open in new window遇到的场景并不多

const obj = [
  {
    name: 'frank',
    age: 123,
  },
  {
    name: 'chang',
    age: 124,
  },
  {
    name: 'chang',
    age: 123,
  },
]
// 使用filter和Map
function uniqueFunc(arr, uniId) {
  const res = new Map()
  return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1))
}
// 使用reduce
function uniqueFunc2(arr, uniId) {
  let hash = {}
  return arr.reduce((accum, item) => {
    if (!hash[item[uniId]]) {
      hash[item[uniId]] = true
      accum.push(item)
    }
    return accum
  }, [])
}
// 使用for循环
function uniqueFunc3(arr, uniId) {
  let obj = {}
  let tempArr = []
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i][uniId]]) {
      tempArr.push(arr[i])
      obj[arr[i][uniId]] = true
    }
  }
  return tempArr
}

数组对象对比找出差异项

写公司业务遇到了这个问题,需要对比两个对象数组找出差异项,这种场景普遍是两个数据对象是一个包含另一个的关系,也就是一个是另一个的子数组

自然想到了用forEach ,请注意如果数组在迭代时被修改了,则其他元素会被跳过open in new window

var words = ['one', 'two', 'three', 'four']
words.forEach(function (word) {
  console.log(word)
  if (word === 'two') {
    words.shift()
  }
})
// one
// two
// four

所以外层数组必须是内层数组的子数组

let arr1 = [{ Num: 'A' }, { Num: 'B' }]
let arr2 = [
  { Num: 'A', Name: 't1' },
  { Num: 'B', Name: 't2' },
  { Num: 'C', Name: 't3 ' },
]
arr1.forEach((item) => {
  arr2.forEach((item2, index) => {
    if (item.Num === item2.Num) {
      arr2.splice(index, 1)
    }
  })
})

console.log(arr2) //  [ { Num: 'C', Name: 't3 ' } ]

另外一种比较讨巧,也很好理解。就是把对象数组中的每一项的唯一标识单独搞成一个数组,这样处理起来就简单很多了。你也不需要像上面那两种方式考虑那么多

let arr1 = [{ Num: 'A' }, { Num: 'B' }]
let arr2 = [
  { Num: 'A', Name: 't1' },
  { Num: 'B', Name: 't2' },
  { Num: 'C', Name: 't3 ' },
]
let arr1Num = []
arr1.forEach((item) => {
  arr1Num.push(item.Num)
})
let result = arr2.filter((v) => arr1Num.indexOf(v.Num) === -1)

console.log(result) // [ { Num: 'C', Name: 't3 ' } ]

delete数组元素

let arr = ['I', 'go', 'home']

delete arr[1] // remove "go"

alert(arr[1]) // undefined

alert(arr.length) // 3

使用 delete 删除指定索引号的数组元素后会发生什么?

  • 数组元素值消失
  • 通过索引号访问,得到 undefined
  • 数组长度不变
上次编辑于:
本站勉强运行 小时
本站总访问量
網站計數器