3
\$\begingroup\$

I have the following code that converts a string that looks like:

aaa-bbb|ccc-ddd|eee-fff

to two strings that look like:

aaa|ccc|eeeandbbb|ddd|fff

The code works fine, but I am wondering if I probably missed some string/array functions that can makes the job in fewer operations / or with faster runtime.

var id = "HEL-CAS|MAD-STO|XXX-YYY"
var splittedId = id.split('|');
var from = "",
  to = "";
$(splittedId).each(function(a, b) {
  from = from + b.split("-")[0] + "|";
  to = to + b.split("-")[1] + "|";
});
from = from.substring(0, from.length - 1);
to = to.substring(0, to.length - 1);
\$\endgroup\$
2
\$\begingroup\$

You can use some ES6 functions and have something like:

var s = 'HEL-CAS|MAD-STO|XXX-YYY';
var s1 = [];
var s2 = []

for (var v of s.split('|').map(str => str.split('-'))) {
  s1.push(v[0])
  s2.push(v[1])
}

s1.join('|')
s2.join('|')
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

You can make from and to to array and use array.join(). This might help you if you wish to process certain values in this list later.

var str = "HEL-CAS|MAD-STO|XXX-YYY"
var from = [], to = [];
str.split('|').forEach(function(item){
  var _tmp = item.split("-");
  from.push(_tmp[0]);
  to.push(_tmp[1]);
});

console.log(from.join("|"), to.join("|"));

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You probably meant from.join("|") .. but still I would love to have some profiler information between the two versions (mine and yours) \$\endgroup\$ – najibla Feb 10 '16 at 11:52
  • \$\begingroup\$ @najibla Inspired by your question, I actually widened its requirement so rather than an answer I posted it as a new question. You can look at it [here] (codereview.stackexchange.com/questions/119722/…). \$\endgroup\$ – cFreed Feb 12 '16 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy