Concat elements within array

Viewed 70

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

4 Answers

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

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

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

One could implement an unzip method for list-like structures, and based on that concatenate the unzipped array items via a simple forEach task ...

function unzip(listLike, forceEven = false) {
  const arr = Array.from(listLike ?? []);

  const left = [];
  const right = [];

  for (let idx = 0; idx < arr.length; idx = idx + 2) {
    left.push( arr[idx] );

    if (arr.hasOwnProperty(idx + 1)) {
      right.push( arr[idx + 1] );
    }
  }
  if (forceEven === true) {
    left.length = right.length;
  }
  return [ left, right ];
}
let arr = ['1', '2', '3', '4', '5', '6', '7'];


// test of `unzip` implementation.
console.log(
 'test of `unzip` implementation ...',
 { arr, unzipped: unzip(arr),
});


// solving the OP's problem.
let right;

{ [arr, right] = unzip(arr, true) };

console.log(
  'evenly `unzip` and reassign `arr` ...',
  { arr, right },
);

arr.forEach((item, idx) =>
  arr[idx] = item + right[idx]
);
console.log(
  'result of unzipped and concatenated `arr` items ...',
  { arr },
);


// solving the OP's problem for an unevenly unzipped array.

arr = ['1', '2', '3', '4', '5', '6', '7'];
right;

{ [arr, right] = unzip(arr) };

console.log(
  'unevenly unzipped and reassigned `arr` ...',
  { arr, right },
);

arr.forEach((item, idx) =>
  arr[idx] = item + (right[idx] ?? '')
);
console.log(
  'result of unevenly unzipped and concatenated `arr` items ...',
  { arr },
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Related