0
function product() {
    return Array.prototype.reduce.call(arguments, function(as, bs) {
        return [a.concat(b) for each (a in as) for each (b in bs)]
    }, [[]]);
}


arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']];
alert(product(['4','4A','4B'],['16D','15D'],['5d','5e']);

The above works but the following don't work:

arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']];
alert(product(arr4);

Thanks for suggestions

2
  • 1
    What kind of syntax is [a.concat(b) for each (a in as) for each (b in bs)]? You sure you're using JavaScript, and not Python? Commented Feb 21, 2012 at 21:58
  • 1
    @Rocket: for each (.. in ..) is a Mozilla-supported extension to JavaScript which is not currently part of the ECMAScript standard (only part of an offshoot of the standard) and therefore may not be supported in non-Mozilla browsers such as Chrome or Internet Explorer or Safari. I would caution against using it. It's actually very good style, but one should be using [].map and [].forEach and [].filter and [].reduce etc. instead, which are standards-compliant and widely supported. (If you aren't happy using those, use jQuery's slightly-broken $.each or $.map.) Commented Feb 21, 2012 at 22:23

1 Answer 1

3

You can have either one or the other; otherwise it's poorly defined. (Unless you want to make the very questionable decision to do special-casing like "if my first argument is an array and each element is an array, return something different". Then you'll be remaking PHP in no time. =])


Use the somefunction.apply method instead; that's what it was made for. For example:

product.apply(this, arr4)

Is equivalent to:

product(arr4[0], arr4[1], ...)

If you do this a lot, you can define product2(arrays) {return product.apply(this,arrays)}.


However unless you want to do both product([..], [..], ..) and product([[..],[..],..]), this seems inelegant.

If you want this function to behave by default like product([[..],[..],..]), then the correct way to solve this is to modify the function to suit your needs. It is currently using the default "variadic" (multiple arguments) arguments variable special to javascript, which stands for an array representing all the arguments you passed into the function. This is not what you want, if you want normal-style fixed-number-of-arguments functions. First add in the appropriate parameter:

function product(arrays) {
    ...
}

and rather than using the default arguments variable, replace that with arrays.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.