js将数组分割成每3个一组

3,711 阅读1分钟
    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    // 第一种方式
    const result = []
    for (let i = 0; i < arr.length; i += 3) {
      result.push(arr.slice(i, i + 3))
    }

    // 第二种方式
    const result1 = arr.reduce((acc, curr, index) => {
      if (index % 3 === 0) acc.push([])
      acc[Math.floor(index / 3)].push(curr)
      return acc
    }, [])

    console.log(result) // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
    console.log(result1) // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

需求:将valueList中的值依次填入list中type为b的value中

    const list = [
      { type: 'a', value: 'a' },
      { type: 'b', value: 'b' },
      { type: 'c', value: 'c' },
      { type: 'a', value: 'a' },
      { type: 'b', value: 'b' },
      { type: 'c', value: 'c' },
      { type: 'a', value: 'a' },
      { type: 'b', value: 'b' },
      { type: 'c', value: 'c' },
      { type: 'a', value: 'a' },
      { type: 'b', value: 'b' },
      { type: 'c', value: 'c' }
    ]

    const valueList = ['b1', 'b2', 'b3', 'b4']

第一种方式:将list转为二维数组,遍历赋值

    const list1 = list.reduce((acc, curr, index) => {
      if (index % 3 === 0) acc.push([])
      acc[Math.floor(index / 3)].push(curr)
      return acc
    }, [])

    list1.forEach((item, index) => {
      for (const item1 of item) {
        if (item1.type === 'b') item1.value = valueList[index]
      }
    })

    console.log(list1)

image.png

第二种方式:shift方法

    for (const item of list) {
      if (item.type === 'b') item.value = valueList.shift() // shift()删除第一个元素,并返回此元素
    }

    console.log(list)
    console.log(valueList) // []