Flatten Javascript array

前端 未结 5 1238
悲&欢浪女
悲&欢浪女 2021-01-29 12:36

I have an array of objects like this:

let list = [
  {
    \'items\': [
      \'item 1\',
      \'item 2\'
    ]
  },
  {
    \'items\': [
      \'item 3\'
    ]         


        
5条回答
  •  臣服心动
    2021-01-29 13:12

    There are multiple ways you can achieve this:

    const list = [{'items': ['item 1','item 2']},{'items': ['item 3']}]
    
    // Using map and flat
    console.log(list.map(o => o.items).flat())
    
    // Using flatMap
    console.log(list.flatMap(o => o.items))
    
    // Using reduce
    console.log(list.reduce((a, o) => a.concat(o.items), []))
    
    // Using a plain old for loop (wrapped in a function)
    const getItems = list => {
      let temp = []  
      for (let i = 0; i < list.length; i++) {
        const items = list[i].items
        for (let j = 0; j < items.length; j++) {
          temp.push(items[j])
        }
      }
      return temp
    }
    console.log(getItems(list))

    However, if you want a performance-first solution, reduce + for loop is the way to go:

    const list = [{'items': ['item 1','item 2']},{'items': ['item 3']}]
    
    console.log(list.reduce((a, o) => {
      for (var i = 0; i < o.items.length; i++) a.push(o.items[i])
      return a
    }, []))

    Check this jsperf for test cases.

提交回复
热议问题