user7558372
user7558372

Reputation:

Concat arrays in array of objects

I build this array:

const array = [
  {
    title: 'something',
    list: ['a', 'b', 'c', 'd']
  },
  {
    title: 'dog',
    list: ['aa']
  },
  {
    title: 'cat',
    list: ['aaa', 'b', 'cccc']
  },
  {
    title: 'apple',
    list: [],
  }
]

I would like an array containing all the values in the other arrays, so:

const res = ['a', 'b', 'c', 'd', 'aa', 'aaa', 'b', 'cccc']

I can I do that? I can use concat but how?

Upvotes: 2

Views: 1443

Answers (5)

andydavies
andydavies

Reputation: 3293

Forget flatmap and reduce. Keep things simple and easy to understand.

var res = []
for (var i = 0; i < array.length; i++) {
    res = res.concat(array[i]["list"])
}

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122037

You could use concat on empty array with map and spread syntax ....

const array = [{"title":"something","list":["a","b","c","d"]},{"title":"dog","list":["aa"]},{"title":"cat","list":["aaa","b","cccc"]},{"title":"apple","list":[]}]

const res = [].concat(...array.map(({list}) => list))
console.log(res)

Upvotes: 1

Prince Hernandez
Prince Hernandez

Reputation: 3721

using reduce and the ...(spread operator) it is very simple to do.

const array = [{
    title: 'something',
    list: ['a', 'b', 'c', 'd']
  },
  {
    title: 'dog',
    list: ['aa']
  },
  {
    title: 'cat',
    list: ['aaa', 'b', 'cccc']
  },
  {
    title: 'apple',
    list: [],
  }
]

const result = array.reduce((accum, item) => {
  return [...accum, ...item.list]
}, [])

console.log(result);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could reduce the array for flattening a property.

const
    array = [{ title: 'something', list: ['a', 'b', 'c', 'd'] }, { title: 'dog', list: ['aa'] }, { title: 'cat', list: ['aaa', 'b', 'cccc'] }, { title: 'apple', list: [] }],
    list = array.reduce((r, { list }) => [...r, ...list], []);

console.log(list);

Or take maybe upcoming flatMap.

const
    array = [{ title: 'something', list: ['a', 'b', 'c', 'd'] }, { title: 'dog', list: ['aa'] }, { title: 'cat', list: ['aaa', 'b', 'cccc'] }, { title: 'apple', list: [] }],
    list = array.flatMap(({ list }) => list);

console.log(list);

Upvotes: 3

ellipsis
ellipsis

Reputation: 12152

Use concat and reduce together

var a=[
  {
    title: 'something',
    list: ['a', 'b', 'c', 'd']
  },
  {
    title: 'dog',
    list: ['aa']
  },
  {
    title: 'cat',
    list: ['aaa', 'b', 'cccc']
  },
  {
    title: 'apple',
    list: [],
  }
];
console.log(a.reduce((acc,e)=>acc.concat(e.list),[]))

Upvotes: 1

Related Questions