Search code examples
javascriptreturnmultiple-return-values

Assigning elements from returned array where index is 1 or higher


Given is a function, that returns an array with (n) elements. I want to assign these return values, but not the first one.

// match returns ["abc123","abc","123"] here  
[ foo, bar ] = "abc123".match(/([a-z]*)([0-9]*)/);

Now I've got

foo = "abc123"
bar = "abc"

But my intention had been

foo = "abc"
bar = "123"

In other languages you can do stuff like

//pseudocode  
[_,foo,bar] = "abc123".match(/([a-z]*)([0-9]*)/);

To archive this, but how is it done in JS?

Surely, one could do

[garbage,foo,bar] = "abc123".match(/([a-z]*)([0-9]*)/);
garbage = undefined;

.. but,.. urgh..


Solution

  • I'm assuming you're using ES6 (ECMAScript 2015, the latest version of JavaScript). If so, your pseudocode was really close, you just don't even need a variable name in the first position, you can just leave it off entirely:

    [ , foo, bar] = "abc123".match(/([a-z]*)([0-9]*)/);
    

    Note the leading comma. That stores the value from index 1 in foo and the value from index 2 in bar.

    Live Example on Babel's REPL

    You can do that at any point in the sequence on the left. For instance, let's pretend that you wanted foo to be the value from 0 and bar to be the value from 2:

    // Different from what the question asks, an example
    // of grabbing index 0 and index 2
    [foo, , bar] = "abc123".match(/([a-z]*)([0-9]*)/);
    

    Since we didn't put anything in the second position on the left, it's skipped during the deconstructing assignment.