Flatten Javascript array

前端 未结 5 1230
悲&欢浪女
悲&欢浪女 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.

    0 讨论(0)
  • 2021-01-29 13:14

    You could use reduce(). There is no way to avoid looping since Array prototype methods do loops internally

    let list = [
      {
        'items': [
          'item 1',
          'item 2'
        ]
      },
      {
        'items': [
          'item 3'
        ]
      }
    ];
    
    const res = list.reduce((a,c) => [...a, ...c.items],[])
    
    console.log(res)

    0 讨论(0)
  • 2021-01-29 13:15

    https://lodash.com/docs/4.17.14#flatten

    And

    https://lodash.com/docs/4.17.14#flattenDeep

    Look like they're exactly what you need.

    0 讨论(0)
  • 2021-01-29 13:16

    you can use the Array.reduce method and follow the docs here

    {
        let list = [
          {
            'items': [
              'item 1',
              'item 2'
            ]
          },
          {
            'items': [
              'item 3'
            ]
          }
        ];
    
        /**
        * @parameter {Array} arg
        */
        function splat (arg) {
            return arg.reduce((total, { items }) => [...total, ...items], []);
        }
    
        console.log(splat(list));
    }
    

    You could also play with recursive function to make a more generic function that accepts array of nested objects.

    0 讨论(0)
  • 2021-01-29 13:34

    You can flat the map() result using Array.prototype.flatMap():

    The flatMap() method first maps each element using a mapping function, then flattens the result into a new array.

    let list = [
      {
        'items': [
          'item 1',
          'item 2'
        ]
      },
      {
        'items': [
          'item 3'
        ]
      }
    ]
    list = list.flatMap(i => i.items);
    
    console.log(list);

    0 讨论(0)
提交回复
热议问题