简体   繁体   中英

How to join two arrays into one two-dimensional array?

I have two arrays. How can I join them into one multidimensional array?

The first array is:

var arrayA = ['Jhon, kend, 12, 62626262662', 
              'Lisa, Ann, 43, 672536452', 
              'Sophie, Lynn, 23, 636366363'];

My other array has the values:

var arrayB = ['Jhon', 'Lisa', 'Sophie']; 

How could I get an array with this format??

var jarray = [['Jhon', ['Jhon, kend, 12, 62626262662']], 
              ['Lisa', ['Lisa, Ann, 43, 672536452']], 
              ['Sohphie', ['Sophie, Lynn, 23, 636366363']]]
var jarray = [];
for (var i=0; i<arrayA.length && i<arrayB.length; i++)
    jarray[i] = [arrayB[i], [arrayA[i]]];

However, I wouldn't call that "multidimensional array" - that usually refers to arrays that include items of the same type. Also I'm not sure why you want the second part of your arrays be an one-element array.

Here is a map version

 var arrayA = ['Jhon, kend, 12, 62626262662', 'Lisa, Ann, 43, 672536452', 'Sophie, Lynn, 23, 636366363']; var arrayB = ['Jhon', 'Lisa', 'Sophie']; /* expected output var jarray = [['Jhon', ['Jhon, kend, 12, 62626262662']], ['Lisa', ['Lisa, Ann, 43, 672536452']], ['Sohphie', ['Sophie, Lynn, 23, 636366363']]] */ var jarray = arrayB.map(function(item,i) { return [item,[arrayA[i]]]; }); console.log(jarray); 

You can use Underscore.js http://underscorejs.org/#find Looks through each value in the list, returning the first one that passes a truth test (iterator). The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.

var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2

Then, you can make the same with the array B elements and by code, make a join.

This is what I did to get what you were asking:

var jarray = [];
for (var i = 0; i < arrayB.length; i++) {
    jarray[i] = [];
    jarray[i].push(arrayB[i]);
    var valuesList = [],
        comparator = new RegExp(arrayB[i]);
    for (var e = 0; e < arrayA.length; e++) {       
        if (comparator.test(arrayA[e])) {
            valuesList.push(arrayA[e]);
       }        
    }
    jarray[i].push(valuesList);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM