1

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

2
  • do you want to keep the object reference? (aka mutating the variable?) Commented Aug 31, 2022 at 15:16
  • I won't flag it as a duplicate because it's a pretty messy question, but there's another viable answer here: Merge every two elements into 1 element in javascript array Commented Aug 31, 2022 at 15:22

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I wonder if the OP has a requirement relating to odd length arrays. I think this will index past the end of x
@danh good question. Array will always be of an even length
1

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

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.