Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize array with one element, or push element if array exists

Let's say you have a hash o of arrays; for example registered callbacks for events, when each event can have 0 or more callbacks.

Is there a better way to say this in ES6?

if (key in o) o[key].push(x); else o[key] = [x]

By "better" I mean more easily understood by other developers. Possibly more concise, but not at the expense of readability. A particular (common) problem is that o is often a longer expression, e.g. this.listeners, and repeating it three times seems suboptimal. So real code might look like this:

if (event in this.listeners)
    this.listeners[event].push(callback);
else
    this.listeners[event] = [callback];
like image 445
Dan Dascalescu Avatar asked Jan 31 '17 07:01

Dan Dascalescu


People also ask

How to push an element in an array in JavaScript?

Sometimes you want to push single or multiple items in an array. So you can use the JavaScript push () method to add elements in an array. If you work with javascript arrays, you should read this javascript array posts: The javaScript push () method is used to add a new element to the end of an array.

How to initialize an array with the same value in C?

Below are some of the different ways in which all elements of an array can be initialized to the same value: Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. This will initialize the num array with value 1 at all index.

How to add an element to the end of an array?

If you work with javascript arrays, you should read this javascript array posts: The javaScript push () method is used to add a new element to the end of an array. Note: javaScript push () array method changes the length of the given array.

How to check if an item exists in an array?

For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf () and if it doesn't then just push the item into the array: Show activity on this post. Show activity on this post.


1 Answers

By using the logical nullish assignment ??=, you could check the property and if it is undefined or null, create a new array.

(o[key] ??= []).push(x);

Older approach:

You could use a logical OR and create an array if necessary.

o[key] = o[key] || [];
o[key].push(x);
like image 175
Nina Scholz Avatar answered Oct 21 '22 02:10

Nina Scholz