Home > Back-end >  Concat elements within array
Concat elements within array

Time:09-01

Trying to concat elements within in an array for example:

const x = ['1', '2', '3', '4', '5', '6']

becomes

const x = ['12', '34', '56']

The most straight-forward solution for me would be to manually loop through the array, create a new element, combining current index and index 1, then splice the array, inserting the new element and removing the 2.

However, I am looking for something more concise if anyone has ever encountered this problem before.

Any help is v much appreciated. Thanks

CodePudding user response:

You could assign to new indices and adjust the length of the array.

const
    x = ['1', '2', '3', '4', '5', '6'];

let i = 0;

while (i * 2 < x.length) x[i] = x[i * 2]   x[i   * 2   1];

x.length = i;

console.log(x);

CodePudding user response:

First break the array down in chunks.. You can make the chunk size configurable as follows

function chunkify(arr, size) {

    let arr2 = [];
    let subArr = [];

    for (let i = 0; i < arr.length; i  = size) {
        subArr = arr.slice(i, i   size);
        arr2.push(subArr.join(''));
    }
  
    return arr2;
}

And then use it like

const x = ['1', '2', '3', '4', '5', '6'];
const y = chunkify(x, 2);
console.log(y); //  ['12', '34', '56']

CodePudding user response:

If a non-mutating approach is acceptable, the idea of concatenating odd indexes with their predecessor can be coded fairly concisely with reduce...

const pairsOf = x =>
  x.reduce((a,n,i) => (i%2 ? a[a.length-1] =n : a.push(n), a), []);
 
console.log(pairsOf(['1', '2', '3', '4', '5', '6']));
console.log(pairsOf(['1', '2', '3', '4', '5', '6', '7']));

  • Related