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

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
j.b
  • 151
  • 1
  • 7
  • 17
  • 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? – gen_Eric Feb 21 '12 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`.) – ninjagecko Feb 21 '12 at 22:23

1 Answers1

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.

ninjagecko
  • 88,546
  • 24
  • 137
  • 145