1
\$\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|eee and bbb|ddd|fff.

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

The code works fine, but I am wondering if it's possible to do this in fewer operations / or with faster runtime.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Yes, there are few built-in array functions you may use to simplify your code. I don't think you will ever notice any performance difference but code will also be easier to read:

var id = "HEL-CAS|MAD-STO|XXX-YYY" 

// Format is fixed then it's easy to use a regex
var splittedId = id.split(/[\|-]/);

// Now we can pick "every other element" and then join strings
var from = splittedId.filter(function (v, i) {
    return i & 1 == 0;
}).join('|');

var to = splittedId.filter(function (v, i) {
    return i & 1 == 1;
}).join('|');
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.