Convert big collection into simple array Is there a better way to do this?

const data = [{id: 1, name: 'item1'}, {id: 2, name: 'item2'}]
const a = []
data.forEach(x =&gt; { a[x.id] = x.name })
return a // ['1': 'item1', '2': 'item2']
Yes. Use array.reduce and use an object.

const a = data.reduce((items, item) =&gt; (items[item.id] = item.name, items), {});

// a = {1:{...}, 2: {...};


You can still use the bracket notation to access the items, i.e. a[id].

A problem with using IDs as array indices is that you introduce gaps in the array. You also get a false array length. Take the following example:

const a = [];
a[999] = {/* User data */};
a.length // 1000;


You only added a single item, with id "999" but now the array reports 1000 in length. Items 0 to 998 are actually empty.