How to merge specific elements inside an array together - JavaScript

When working with arrays containing mixed data types, you might need to merge consecutive numeric elements while keeping certain separators intact. This is common when processing data that represents grouped numbers.

Let's say we have the following array:

var values = [7,5,3,8,9,'/',9,5,8,2,'/',3,4,8];
console.log("Original array:", values);
Original array: [7, 5, 3, 8, 9, '/', 9, 5, 8, 2, '/', 3, 4, 8]

Using join() and split() Method

To merge specific elements while preserving separators, we can use join(), split(), and map() together:

var values = [7,5,3,8,9,'/',9,5,8,2,'/',3,4,8];

var afterMerge = values.join('')
    .split(/(\d+)/)
    .filter(Boolean)
    .map(v => isNaN(v) ? v : +v);

console.log("After merging:", afterMerge);
After merging: [75389, '/', 9582, '/', 348]

How It Works

The solution works in several steps:

  1. join('') - Converts the array to a string: "75389/9582/348"
  2. split(/(\d+)/) - Splits by digit groups while capturing them: ["", "75389", "/", "9582", "/", "348", ""]
  3. filter(Boolean) - Removes empty strings: ["75389", "/", "9582", "/", "348"]
  4. map(v => isNaN(v) ? v : +v) - Converts numeric strings back to numbers

Alternative Approach Using Reduce

Here's another method using reduce() for more control:

var values = [7,5,3,8,9,'/',9,5,8,2,'/',3,4,8];

var result = values.reduce((acc, curr) => {
    if (typeof curr === 'number') {
        if (typeof acc[acc.length - 1] === 'number') {
            acc[acc.length - 1] = parseInt(acc[acc.length - 1].toString() + curr.toString());
        } else {
            acc.push(curr);
        }
    } else {
        acc.push(curr);
    }
    return acc;
}, []);

console.log("Using reduce:", result);
Using reduce: [75389, '/', 9582, '/', 348]

Comparison

Method Readability Performance Flexibility
join().split() Moderate Good Limited to string operations
reduce() Good Better High - more control over logic

Conclusion

Both methods effectively merge consecutive numeric elements while preserving separators. The join().split() approach is more concise, while reduce() offers greater flexibility for complex merging logic.

Updated on: 2026-03-15T23:19:00+05:30

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements