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.

janos
113k15 gold badges154 silver badges396 bronze badges
asked Feb 10, 2016 at 11:44
\$\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('|');
answered Feb 10, 2016 at 12:04
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.