How to merge specific elements inside an array together - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ]
raja
Published on 09-Nov-2020 11:11:59
Advertisements