-1

I have a multidimensional JavaScript array with some string data.

var array = [];

array[0] = ["A","B","C"];  
array[1] = ["G","H"];  

I want to merge these together into a new array.

Value 1 from the first array should merge with value 1 from array 2 and so on.

Of course, I can do like this.

var array2 = array[0][0] + array[1][0];

But I don't the data so the first array could hold 6 values and there could also be more than 2 arrays.

Is there a way to dynamically iterate over the multidimensional array and create a new array.

8
  • ["A","B","C"].concat(["G","H"]) Commented Aug 12, 2016 at 12:43
  • var array2 = array[0][0] + array[1][0]; array2 = "AG". Commented Aug 12, 2016 at 12:46
  • array.map(x => x[0]) Commented Aug 12, 2016 at 12:47
  • 4
    please add the expected output and the code that you had tried Commented Aug 12, 2016 at 12:47
  • The output should be "AG". Commented Aug 12, 2016 at 12:57

4 Answers 4

1

You can use Array#map and Array#join methods.

// iterate over multi diamensional array and
// generate array with first element of each nested array
var array2 = array.map(function(v){ 
   // retrieve the first element
   return v[0]; 
   // join them to convert into a string as your output
}).join('')

var array = [];

array[0] = ["A", "B", "C"];
array[1] = ["G", "H"];

var array2 = array.map(function(v) {
  return v[0];
}).join('')

console.log(array2);


If you want to do the same with all index then use Array#reduce method.

var array = [];

array[0] = ["A", "B", "C"];
array[1] = ["G", "H"];

// iterate and reduce a single array
var array2 = array.reduce(function(arr, e) {
  // iterate over nested array 
  e.forEach(function(v, i) {
    // concatenate with the elements in parent array
    arr[i] = (arr[i] || '') + v;
  });
  return arr
  // set initial value as array
}, [])

console.log(array2);

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

2 Comments

Perfect. This is exactly what i need. You made my day.
@AlexClaesson : glad to help :)
0

I believe you need to do something like this:

myArray = [["s","m","a"],["d","f"],["t","h","r"]];

function generateStrings(array2d){
    newArray = [];

    function interate(n){
     newString = myArray.reduce((p,c)=>{return c[n]?p+c[n]:p},"")  
     console.log(newString)
     if (newString)newArray.push(newString),interate(n+1)
    }
    interate(0)

    return newArray;
}


generateStrings(myArray);

Comments

0

The most compact way of writing this would be the following:

arrays[0].map((_, i) => arrays.map(array => array[i]).join(''))

Breaking it down:

arrays[0]                     // Starting with the first sub-array,
  .map(                       // create a corresponding array 
    (_, i) =>                 // whose value, for each index is,
      arrays                  // for each of the sub-arrays,
        .map(                 // an array whose values are
          array => array[i])  // the subarray at that index
        )
        .join('')             // with its elements joined together
  );

3 Comments

Uncaught SyntaxError: Unexpected token [ Oops.. You need map((elt
Will this work correctly if arrays[0] is shorter than the other arrays?
No, but I don't know what the desired behavior is in that case.
0

You can use a simple reduce function to merge the Array.

const arr = [ [1, 2, 3], [4, 5] ];
const newArr = arr.reduce((acc, x) => [...acc, ...x], [])

console.log(newArr) // [1, 2, 3, 4, 5]

If you need to create an String object after the merge you just have to apply join('') on the returned array.

With Concat

This is the concat version of the function in case you want to use it.

const newArr = arr.reduce((acc, x) => acc.concat(...x), [])

2 Comments

This is a very clumsy way to do [].concat(...arr), which is not what the OP wants to do anyway.
Sure you can use concat too, but it wont look as good. Your choice.

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.