Night Coder

JavaScript: [].concat() Trick for making a union of items easily

If you don’t know an array is real array or is null (it happens when interacting with database most), and you want to have a union of items like mentioned users id, you can just use this:

const doc = {
    mentionIds: ['id_1'],
    interactedUserIds: null, // can be array value
    creatorId: 'id_2'
};
[].concat(doc.mentionIds, doc.interactedUserIds, doc.creatorId, ['id_3', 'id_4'])

// -> ['id_1', null, 'id_2', 'id_3', 'id_4']

If you want to delete null or undefined values, so:

[].concat(doc.mentionIds, doc.interactedUserIds, doc.creatorId, ['id_3', 'id_4'])
  .filter(item => Boolean(item));

// -> ['id_1', 'id_2', 'id_3', 'id_4']

Leave a Reply

Your email address will not be published. Required fields are marked *