1

I have a array like

var arr = [["one", "two"],["three", "four"],["five", "six", "seven"],["eight", "nine"]];

I am trying to make all the elements unite the elements, but the elements in the same sub-array must not replicate. like:

var output = ["one three four five six seven eight nine","two three four five six seven eight nine"];

This will be added based on number of elements in the first sub array. I tried it but couldn't find any solution. Can anyone help.?
This is my code i tried :

function big_for( data ){
    var aj = [];
    var k = 0;
    for( var i = 0; i < data.length; i++ ){
        for( var j = 0; j < data[i].length; j++ ){
            aj[k] = data[i][j];
            k++;
        } 
    }
    return arr;
    }

Thanks in advance.!

hemnath mouli
  • 2,617
  • 2
  • 17
  • 35
  • might be duplicate of: http://stackoverflow.com/questions/27266550/how-to-flatten-nested-array-in-javascript – ItayB Mar 13 '16 at 15:21
  • 1
    Does it then go "three one two four five six seven eight nine"? If not I don't see the correlation between your input and your expected output. – Andy Mar 13 '16 at 15:24
  • You can flatten your array. this might be the answer http://stackoverflow.com/questions/10865025/merge-flatten-a-multidimensional-array-in-javascript – Rafael Grillo Mar 13 '16 at 15:25
  • @RafaelGrillo, look at the expected output. A simple flatten is not the answer. – Andy Mar 13 '16 at 15:26
  • The output must be 1st sub array's element with all other elements. Therfore number of array in output will the count of first sub array. Got it.? – hemnath mouli Mar 13 '16 at 15:27
  • So is this for some sort of coding test or something? Don't really see what business case this would be needed for. – David Mar 13 '16 at 15:34
  • @David custom filter – hemnath mouli Mar 13 '16 at 15:35

1 Answers1

6

Sorry @Andy

var arr = [["one", "two"],["three", "four"],["five", "six", "seven"],["eight", "nine"]];

var base = arr.shift();
var result = base.map(function(init) {
    return [].concat.apply([], [init].concat(arr)).join(' ');
});
Rafael Grillo
  • 232
  • 2
  • 8
  • Oh I haven't used `shift` and `concat` before. Can you explain both. Oh ya this worked.! Thanks. – hemnath mouli Mar 13 '16 at 15:33
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift Shift will remove the first element of the array and return it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat Concat will simply concatenate a array with another array – Rafael Grillo Mar 13 '16 at 15:35
  • What if I need second array to be in gendral.? Now the first is in gendral. – hemnath mouli Mar 13 '16 at 16:31