Concatenating the elements of an array

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 into the array as follows:

var array_soma = [
                   "parte 1",
                   "parte 1 parte 2",
                   "parte 1 parte 2 parte 3",
                   "parte 1 parte 2 parte 3 parte 4",
                 ];
    
asked by anonymous 07.07.2018 / 02:14

2 answers

2

It's simple, you need to save the first position and mount the second one on the previous one so on.

Using for starting from 1 on, 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);
    
07.07.2018 / 02:18
1

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

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 concatenates between el (current element) and the last one already in the list, res[res.length - 1] .

    
07.07.2018 / 02:50