Skip to content Skip to sidebar Skip to footer

Flatten Javascript Array

I have an array of objects like this: let list = [ { 'items': [ 'item 1', 'item 2' ] }, { 'items': [ 'item 3' ] } ] and I want flatten th

Solution 1:

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);

Solution 2:

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)

Solution 3:

There are multiple ways you can achieve this:

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

// Using map and flatconsole.log(list.map(o => o.items).flat())

// Using flatMapconsole.log(list.flatMap(o => o.items))

// Using reduceconsole.log(list.reduce((a, o) => a.concat(o.items), []))

// Using a plain old for loop (wrapped in a function)constgetItems = list => {
  let temp = []  
  for (let i = 0; i < list.length; i++) {
    const items = list[i].itemsfor (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.

jsperf screenshot

Solution 4:

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
    */functionsplat (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.

Solution 5:

Post a Comment for "Flatten Javascript Array"