Concatenation of items from a nested loop array

Asked

Viewed 283 times

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]" ]

2 answers

1


The real problem is ifs using 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 this amendment already works a[i][j].split(',') it doesn’t 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 the toString() then turn back into the same String who had originally.

So the concatenation should be done like this:

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

But why complicate something simple ? Use method join of Array which was made for this very purpose, to bring together all the elements into one String 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 the push to stay in the style of what I had.

Edit:

If it is necessary to apply the trim just add a map before the join to map all elements to your version trimmed:

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);

  • 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 the trim(). 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 the trim() to words before concatenation.

  • 1

    @Eden Yes, sir, just make one map before the join. I’ve already edited the answer to contemplate this scenario too.

0

If the original array is always with 2 subitens, you can do so:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.