How to merge specific elements inside an array together - JavaScript



Let’s say the following is our array −

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

To merge specific elements, use map along with split().

Example

Following is the code −

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

To run the above program, you need to use the following command −

node fileName.js. 

Here, my file name is demo301.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo301.js [ 75389, '/', 9582, '/', 348 ]
Updated on: 2020-11-09T11:11:59+05:30

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements