0
I would like to pick up the items in var a
, a Bi-dimensional Array, and make an iteration in a nested loop, concatenating everything in order to place them between brackets, separated by a bar, as shown by the desired result below, which will be stored in var b
. The problem is that bars and brackets don’t stay 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]" ]
Isac, it was perfect his simplest solution. The problem is that
var a
is originally generated from a function that makes the words random, making it possible to have spaces at the beginning and end of each word, so I used thetrim()
. Ex:var a = [ ['advice ', ' advices'], [' are', 'is '] ];
. Upshot:var b = [ '[advice / advices]' '[ are / is ]' ];
. There’s room before are and after is and, as is random,var a
can end with initial and final spaces in any of the words. You can apply thetrim()
to words before concatenation.– eden
@Eden Yes, sir, just make one
map
before thejoin
. I’ve already edited the answer to contemplate this scenario too.– Isac