Reputation: 69
I want from this string :
'Paris , Bruxelles , Amsterdam , Berlin'
Get this result in an array :
['Paris_Bruxelles' , 'Bruxelles_Amsterdam' , 'Amsterdam_Berlin' ]
Can anyone help me please ?
Upvotes: 1
Views: 61
Reputation: 26181
Basically in functional languages you are expected to use a zipWith
function, where the accepted answer mimics that in JS with side effects.
However you may also mimic Haskell's pattern matching in JS and come up with a recursive solution without any side effects
var cities = "Paris , Bruxelles , Amsterdam , Berlin , Bayburt".split(/\s*,\s*/),
pairs = ([f,s,...rest]) => s == void 0 ? []
: [f + "_" + s].concat(pairs([s,...rest]));
console.log(pairs(cities));
Upvotes: 0
Reputation: 386660
You could split the string and slice the array and get the pairs.
var string = 'Paris , Bruxelles , Amsterdam , Berlin',
array = string.split(/\s*,\s*/),
result = array.slice(1).map((s, i) => [array[i], s].join('_'));
console.log(result);
Upvotes: 3