Question: I've got some data like this:

```
const items = [
  { _id: '1', reference: ['abc'] },
  { _id: '2', reference: ['def'] },
  { _id: '3', reference: ['abc'] }
]

```

The length of `items` is always different.

Now I need to get all unique reference strings in a single array. So the result should be

```
['abc', 'def']

```

as `'abc'` is a duplicate.

I tried to use a `forEach()` loop:

```
const references = []
items.forEach(i => {
  references.concat(i.reference)
})

console.log(references)

```

But `references` just gets an empty array result. Also with that I did not take care of duplicates...

---

I would like to use an ES6 pattern. With that I know I could use something like this:

```
const array1 = ['abc']
const array2 = ['def']
const array3 = Array.from(new Set(array1.concat(array2)))

```

But how can I do this using a loop to get every reference array of each item object - even if I do not know how many objects are in the item array?

Answer: 
If you wanna do a functional style (map-reduce), you can do it like this 

```js
const items = [
  { _id: '1', reference: ['abc'] },
  { _id: '2', reference: ['def'] },
  { _id: '3', reference: ['abc'] }
]

// extract references and put them into a single array
const references = 
  items
    .map(x => x.reference)
    .reduce((prev, cur) => prev.concat(cur))

// put them in a set to dedupe
const set = new Set(references)

console.log(references)
console.log([...set])
```

If you want to do fewer passes over the data, and also avoid the need for `Set` you could do.

```js
const items = [
  { _id: '1', reference: ['abc'] },
  { _id: '2', reference: ['def'] },
  { _id: '3', reference: ['abc'] }
]

const result = Object.keys(items.reduce((obj, {reference}) => {
  for (const ref of reference) {
    obj[ref] = true
  }
  return obj;
}, {}))

console.log(result)
```

You can also trade expressiveness for performance with a fully imperative approach below. 

```js
const items = [
  { _id: '1', reference: ['abc'] },
  { _id: '2', reference: ['def'] },
  { _id: '3', reference: ['abc'] }
];

const occ = {};
const references = [];
for (let i = 0; i < items.length; ++i) {
  const refs = items[i].reference;
  for (let j = 0; j < refs.length; ++j) {
    const ref = refs[j];
    if (occ[ref] == null) {
      references.push(ref);
      occ[ref] = true;
    }
  }
}

console.log(references)

```
If you want to use Sets, you can use `Set.add`, and [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax):

```js
const items = [
  { _id: '1', reference: ['abc'] },
  { _id: '2', reference: ['def'] },
  { _id: '3', reference: ['abc'] }
]

var references = new Set();
items.forEach(i => references.add(...i.reference))
console.log(Array.from(references))
```