Search code examples
javascriptarraysarray-merge

how to merge the value or index in array


how to merge the value or merge the index,
for example I have :

var input = [
            ["0001", "Roman Alamsyah", "Bandar Lampung", "21/05/1989", "Membaca"],
            ["0002", "Dika Sembiring", "Medan", "10/10/1992", "Bermain Gitar"],      
        ];

and I want my array to be

var output = [
            ["0001", "Roman Alamsyah", "Bandar Lampung 21/05/1989", "Membaca"],
            ["0002", "Dika Sembiring", "Medan 10/10/1992", "Bermain Gitar"]
        ];

thanks


Solution

  • You could specify the index joinAt, where the next two elements has to be joined and then splice the array with a new string of the spliced parts.

    var array = [
            ["0001", "Roman Alamsyah", "Bandar Lampung", "21/05/1989", "Membaca"],
            ["0002", "Dika Sembiring", "Medan", "10/10/1992", "Bermain Gitar"],
        ],
        joinAt = 2;
    
    array.forEach(function (a) {
        a.splice(joinAt, 0, a.splice(joinAt, 2).join(' '));
    });
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }