Concatenating the elements of an array

Asked

Viewed 357 times

1

I have an array in Javascript:

var array_soma = [
                   "parte 1",
                   "parte 2",
                   "parte 3",
                   "parte 4",
                 ];

I would like to concatenate each element for the array to look like this:

var array_soma = [
                   "parte 1",
                   "parte 1 parte 2",
                   "parte 1 parte 2 parte 3",
                   "parte 1 parte 2 parte 3 parte 4",
                 ];

2 answers

2


It’s simple, you need to save the first position and mount in the second what you have in the previous one so on.

Using a for starting from 1 onwards, example:

var array_soma = [
  "parte 1",
  "parte 2",
  "parte 3",
  "parte 4",
];

var aux = array_soma[0];
for(i = 1; i < array_soma.length; i++)
{
  array_soma[i] = aux + ' ' + array_soma[i]
  aux = array_soma[i];
}

console.log(array_soma);

1

Another interesting way to solve the problem is to build a new result array with the transformation you want. This can be done at the expense of push, that simplifies the problem. You can do push of each element of the original and concatenate with the last element of the new list, if you already have.

Example:

var array_soma = [
   "parte 1",
   "parte 2",
   "parte 3",
   "parte 4",
];

const res = [];
array_soma.forEach((el,idx) => res.push(idx === 0 ? el : res[res.length - 1] + " " + el));

console.log(res);

The res[res.length - 1] + " " + el makes the concatenation between el(current element) and the last one already in the list, the res[res.length - 1].

Browser other questions tagged

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