Concatenating items of an Array in a nested loop

0

I would like to get the items in var a , a two-dimensional Array, and iterate in a nested loop, concatenating everything, to put them in brackets, separated by a slash, as shown by the desired result logo below, which will be stored in var b . The problem is that the bars and brackets do not look the way you expect.

/* 
Resultado Desejado:
Array [ "[advice / advices]", "[are / is]" ]

Resultado Obtido (Indesejado):
Array [ "[advice /advices /", "[are]is]" ]
*/

var a = [
    ['advice', 'advices'],
    ['are', 'is']
];
var b = [];

for (var i = 0; i < a.length; i++) {
    var c = ['['];
    for (var j = 0; j < a[i].length; j++) {

        if (i < a[i].length - 1) {
            c += a[i][j].split(',').toString().trim() + ' /';
        }

        if (i == a[i].length - 1) {
            c += a[i][j].split(',').toString().trim() + ']';
        }
    }
    b.push(c);
}

console.log(b); // Array [ "[advice /advices /", "[are]is]" ]
    
asked by anonymous 22.01.2018 / 02:17

2 answers

1

The problem is even in ifs that uses i when they should use j :

for (var i = 0; i < a.length; i++) {
    var c = ['['];
    for (var j = 0; j < a[i].length; j++) {

        if (i < a[i].length - 1) {
        //  ^--- aqui devia ser j
            c += a[i][j].split(',').toString().trim() + ' /';
        }

        if (i == a[i].length - 1) {
        //  ^--- e aqui também
            c += a[i][j].split(',').toString().trim() + ']';
        }
    }
    b.push(c);
}

Although with this change already working a[i][j].split(',') does not make sense because a[i][j] is a String with a text like 'advice' . Soon split(',') will transform into an array with only one element and toString() will then transform back into the same String it had originally.

So the concatenation should be done like this:

c += a[i][j].trim() + ' /';

But why complicate something simple? Use the method join of Array that was made exactly for this purpose, put all the elements in a single String by placing a separator of your choice:

var a = [
    ['advice', 'advices'],
    ['are', 'is']
];

var b = [];
for (var i = 0; i < a.length; i++) {
    b.push("[" + a[i].join(' / ') + "]");
}

console.log(b);

I kept push to stay in the style of what I had.

Edit :

If you need to apply trim add map before join to map all elements to your trimmed version:

var a = [
    ['advice', 'advices'],
    ['are', 'is']
];

var b = [];
for (var i = 0; i < a.length; i++) {
    b.push("[" + a[i].map(x=>x.trim()).join(' / ') + "]");
}

console.log(b);
    
22.01.2018 / 02:37
0

If the original array is always with 2 subitems, you can do this:

var a = [
    ['advice', 'advices'],
    ['are', 'is']
];
var b = [];

a.forEach(function(e){
   b.push('['+e[0]+' / '+e[1]+']');
});
console.log(b);
    
22.01.2018 / 02:40