如何在JavaScript中合并更多数组

时间:2016-10-17 06:59:21

标签: javascript arrays

我有3个或更多阵列:

    ### Warning:  Using unoptimized lapack ###
    ### Warning:  Using unoptimized lapack ###
    warning: no previously-included files matching '*.pyo' found anywhere in dis
tribution
    warning: no previously-included files matching '*.pyd' found anywhere in dis
tribution
    objdump.exe: C:\Windows\winsxs\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0
.21022.8_none_750b37ff97f4f68b\msvcr90.dll: File format not recognized
    Looking for python27.dll
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\22193\appdata\local\temp\pip-build-aoxj5g\scipy\setup.py",
line 415, in <module>
        setup_package()
      File "c:\users\22193\appdata\local\temp\pip-build-aoxj5g\scipy\setup.py",
line 411, in setup_package
        setup(**metadata)
      File "c:\python27\lib\distutils\core.py", line 111, in setup
        _setup_distribution = dist = klass(attrs)
      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 269, in __init__

      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 313, in fetch_bu
ild_eggs
      File "build\bdist.win-amd64\egg\pkg_resources\__init__.py", line 826, in r
esolve
      File "build\bdist.win-amd64\egg\pkg_resources\__init__.py", line 1092, in
best_match
      File "build\bdist.win-amd64\egg\pkg_resources\__init__.py", line 1104, in
obtain
      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 380, in fetch_bu
ild_egg
      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line
640, in easy_install

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line
670, in install_item

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line
850, in install_eggs

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line
1078, in build_and_install

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line
1064, in run_setup

      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 246, in run_s
etup
      File "c:\python27\lib\contextlib.py", line 35, in __exit__
        self.gen.throw(type, value, traceback)
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 195, in setup
_context
      File "c:\python27\lib\contextlib.py", line 35, in __exit__
        self.gen.throw(type, value, traceback)
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 166, in save_
modules
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 141, in resum
e
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 154, in save_
modules
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 195, in setup
_context
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 243, in run_s
etup
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 273, in run
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 242, in runne
r
      File "build\bdist.win-amd64\egg\setuptools\sandbox.py", line 46, in _execf
ile
      File "c:\users\22193\appdata\local\temp\easy_install-3hk03b\numpy-1.11.2\s
etup.py", line 386, in <module>
        # Raise errors for unsupported commands, improve help output, etc.
      File "c:\users\22193\appdata\local\temp\easy_install-3hk03b\numpy-1.11.2\s
etup.py", line 378, in setup_package
        test_suite='nose.collector',
      File "c:\users\22193\appdata\local\temp\easy_install-3hk03b\numpy-1.11.2\n
umpy\distutils\core.py", line 169, in setup
      File "c:\python27\lib\distutils\core.py", line 151, in setup
        dist.run_commands()
      File "c:\python27\lib\distutils\dist.py", line 953, in run_commands
        self.run_command(cmd)
      File "c:\python27\lib\distutils\dist.py", line 972, in run_command
        cmd_obj.run()
      File "build\bdist.win-amd64\egg\setuptools\command\bdist_egg.py", line 160
, in run
      File "c:\python27\lib\distutils\cmd.py", line 326, in run_command
        self.distribution.run_command(command)
      File "c:\python27\lib\distutils\dist.py", line 972, in run_command
        cmd_obj.run()
      File "c:\users\22193\appdata\local\temp\easy_install-3hk03b\numpy-1.11.2\n
umpy\distutils\command\build_clib.py", line 83, in run
      File "c:\users\22193\appdata\local\temp\easy_install-3hk03b\numpy-1.11.2\n
umpy\distutils\ccompiler.py", line 596, in new_compiler
      File "c:\users\22193\appdata\local\temp\easy_install-3hk03b\numpy-1.11.2\n
umpy\distutils\mingw32ccompiler.py", line 96, in __init__
      File "c:\users\22193\appdata\local\temp\easy_install-3hk03b\numpy-1.11.2\n
umpy\distutils\mingw32ccompiler.py", line 360, in build_msvcr_library
      File "c:\users\22193\appdata\local\temp\easy_install-3hk03b\numpy-1.11.2\n
umpy\distutils\mingw32ccompiler.py", line 274, in generate_def
    ValueError: Symbol table not found

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\22193\ap
pdata\local\temp\pip-build-aoxj5g\scipy\

C:\Python27\Scripts>

想要获得1个合并数组,其结果如下:

 var array1 = [a,b,c];
 var array2 = [c,d];
 var array3 = [e,f];

我该怎么办?请注意:数组输入不受限制。

6 个答案:

答案 0 :(得分:4)

您可以使用组合算法的迭代和递归方法。

&#13;
&#13;
function combine(array) {
    function c(part, index) {
        array[index].forEach(function (a) {
            var p = part.concat([a]);
            if (p.length === array.length) {
                r.push(p.join(''));
                return;
            }
            c(p, index + 1);
        });
    }

    var r = [];

    c([], 0);
    return r;
}

console.log(combine([['a', 'b', 'c'], ['c', 'd'], ['e', 'f']]));
console.log(combine([['a', 'b', 'c'], ['d', 'e'], ['f', 'g'], ['h', 'i', 'j']]));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:2)

尝试使用for循环 Jsfiddle

&#13;
&#13;
var array1 = ["a", "b", "c"];
var array2 = ["c", "d"];
var array3 = ["e", "f"];
var result = [], pushresult = 0;

for (var i = 0; i < array1.length; i++) {
  for (var j = 0; j < array2.length; j++) {
    for (var k = 0; k < array3.length; k++) {
      pushresult = array1[i] + array2[j] + array3[k];
      result.push(pushresult);
    }
  }
}

console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:2)

您似乎正在尝试从多个阵列(集合)中获取 笛卡尔积
使用Array.concat考虑以下ES6解决方案,Array.reduceArray.map函数:

&#13;
&#13;
const flatten = (arr) => [].concat.apply([], arr);
const product = (...sets) =>
    sets.reduce((acc, set) =>
            flatten(acc.map(x => set.map(y => [ ...x, y ]))),
    [[]]);

var array1 = ['a', 'b', 'c'],
    array2 = ['c','d'],
    array3 = ['e','f'];

result = product(array1, array2, array3);

console.log(JSON.stringify(result));
&#13;
&#13;
&#13;

答案 3 :(得分:0)

if you number of array is fixed (not array element) then you can use

<script>
var array1 = ["a","b","c"];
var array2 = ["c","d"];
var array3 = ["e","f"];
var d=[];
for(i in array1){
    for (j in array2){
        for(k in array3){
        d.push(array1[i]+array2[j]+array3[k]);  
        }
    }
}
alert(d);
</script>

答案 4 :(得分:0)

List applicative和monad可以轻松实现这一目标

// Array Applicative  
Array.prototype.ap = function ( ...args )
  {
    const loop = ( acc , [ x , ...xs ] ) =>
      x === undefined
        ? [ this [ 0 ] ( ...acc ) ]
        : x.chain ( a =>
            loop ( acc.concat ( [ a ] ) , xs ) )
    return loop ( [] , args )
  }
 
// Array Monad
Array.prototype.chain = function chain (f)
  {
    return this.reduce ( ( acc , x ) =>
      acc.concat ( f (x) ), [] )
  }

// the hard work is already done
const combinations = ( ...xxs ) =>
  [ ( ...xs ) => xs ] .ap ( ...xxs )

console.log ( combinations ( array1 , array2 , array3 ) )
// [ [ 'a1', 'a2', 'a3' ],
//   [ 'a1', 'a2', 'b3' ],
//   [ 'a1', 'a2', 'c3' ],
//   [ 'a1', 'b2', 'a3' ],
//   [ 'a1', 'b2', 'b3' ],
//   [ 'a1', 'b2', 'c3' ],
//   [ 'b1', 'a2', 'a3' ],
//   [ 'b1', 'a2', 'b3' ],
//   [ 'b1', 'a2', 'c3' ],
//   [ 'b1', 'b2', 'a3' ],
//   [ 'b1', 'b2', 'b3' ],
//   [ 'b1', 'b2', 'c3' ],
//   [ 'c1', 'a2', 'a3' ],
//   [ 'c1', 'a2', 'b3' ],
//   [ 'c1', 'a2', 'c3' ],
//   [ 'c1', 'b2', 'a3' ],
//   [ 'c1', 'b2', 'b3' ],
//   [ 'c1', 'b2', 'c3' ],
//   [ 'd1', 'a2', 'a3' ],
//   [ 'd1', 'a2', 'b3' ],
//   [ 'd1', 'a2', 'c3' ],
//   [ 'd1', 'b2', 'a3' ],
//   [ 'd1', 'b2', 'b3' ],
//   [ 'd1', 'b2', 'c3' ] ]

答案 5 :(得分:0)

对于无限数量的数组,您似乎需要Array.prototype.cartesian()。它可以按如下方式完成;

&#13;
&#13;
Array.prototype.cartesian = function(...a){
  return a.length ? this.reduce((p,c) => (p.push(...a[0].cartesian(...a.slice(1)).map(e => a.length > 1 ? [c,...e] : [c,e])),p),[])
                  : this;
};

var arr1 = ["a","b","c"],
    arr2 = ["c","d"],
    arr3 = ["e","f"],
  result = arr1.cartesian(arr2,arr3);
console.log(JSON.stringify(result));
&#13;
&#13;
&#13;