Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Proper way of creating an array or pushing into it if it already exists

In my code I have an element, and I want to have it in an array: either the array already exists and then I push my element, or it doesn’t and in that case I create the array with this only element:

if (arr) {
  arr.push(elt);
} else {
  arr = [elt];
}

I’m sure there is a better way to do this. I looked into spreading and nullish coalescing operator, but I didn’t find any correct syntax.
Does anybody have an idea on how I could write my lines with a nicer syntax?
Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the expression arr || [] to return an array which is either arr if arr is defined already or [] otherwise. Then you can simply concat the new value to it:

arr = (arr || []).concat([elt])

Note the new value needs to be enclosed in [] to prevent elt values which are arrays from being flattened.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading