数组方法

·  阅读 175

reduce

累加

var arr1 = [1, 2, 3, 4]
// var result1 = arr.reduce((prev, next) => {
//   return prev + next
// }, 0)

var result1 = arr1.reduce((prev, next) => {
  return prev + next
})
console.log('result1', result1)
复制代码

累乘

var arr2 = [1, 2, 3, 4]
var result2 = arr2.reduce((prev, next) => {
  return prev * next
}, 1)
console.log('result2', result2)
复制代码

数组去重

var arr3 = [1, 2, 2, 3, 4]
var result3 = arr3.reduce((prev, next) => {
  if (!prev.includes(next)) {
    return [...prev, next]
  } else {
    return prev
  }
}, [])
复制代码

原生

for (let i = 0; i < arr3.length; i++) {
  if (!res.includes(arr3[i])) {
    res.push(arr3[i])
  } else {
    continue
  }
}
复制代码

最大值/最小值

var arr4 = [1, 2, 3, 4]
var result4 = arr4.reduce((prev, next) => {
  if (prev > next) {
    return prev
  } else {
    return next
  }
})
var result4 = arr4.reduce((prev, next) => {
  return prev > next ? prev : next
})
console.log('result4', result4)
复制代码

原生

let max = arr4[0]
for (let i = 0; i < arr4.length; i++) {
  if (arr4[i] > max) {
    max = arr4[i]
  }
}
复制代码

扁平化

function Flat (arr = []) {
  return arr.reduce((prev, next) => {
    if (Array.isArray(next)) {
      return prev.concat(Flat(next))
    } else {
      return prev.concat(next)
    }
  }, [])
}
复制代码

原生

function Flat (arr) {
  var res = []
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res = res.concat(Flat(arr[i]))
    } else {
      res.push(arr[i])
    }
  }
  return res
}
复制代码

map

单数组

var arr1 = [1, 2, 3, 4]
var result1 = arr1.map(item => {
  return item + 1
})
console.log('result1', result1)
复制代码

数组中包含对象

var arr2 = [
  {
    age: 1,
    name: 'a'
  },
  {
    age: 2,
    name: 'b'
  },
  {
    age: 3,
    name: 'c'
  }
]

var result2 = arr2.map(item => {
  return {
    age: item.age + 1,
    name: item.name
  }
})
console.log('result2', result2)
var result3 = arr2.map(item => {
  return {
    age: item.age + 1
  }
})
console.log('arr2', arr2)
console.log('result3', result3)
复制代码
分类:
前端
标签:
分类:
前端
标签: