先看看数组对象格式:
- const cars = [
- {
- sin: 1011,
- name: '挖土机'
- }, {
- sin: 1013,
- name: '搅拌车'
- }, {
- sin: 1012,
- name: '抓地车'
- }, {
- sin: 1011,
- name: '挖土机2号'
- }
- ]
一般思路:
- const newArr = []
- cars.forEach(item => {
- let count = 0
- newArr.forEach(_item => {
- if (_item.sin === item.sin) {
- count++
- }
- })
- if (count === 0) {
- newArr.push(item)
- }
- })
新思路:
- const newArr = cars.filter((element, index, self) => {
- return self.findIndex(x => x.sin === element.sin) === index
- })
- const newArr = cars.filter((element, index, self) => {
- const i = self.findIndex(x => x.sin === element.sin)
- return i === index
- })
如何只使用一次循环就可以去重呢
- const obj = {}
- const newArr = cars.reduce((cur, next) => {
- obj[next.sin] ? null : obj[next.sin] = true && cur.push(next)
- return cur
- }, [])
写在最后:对比以上三种方法,肯定还是循环越少越好,巧用reduce对代码性能肯定是有提升的,希望能帮到有需要的同学。