Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the id value wrong for the first and last element?

I have a string that looks like the following:

_/_-- Select a Sub-server (optional) --_|_509_,Subserver 509_|_510_,Subserver 510_|_511_Subserver 511

And I am trying to get the following output from it:

const arr = [
    { id: "", text: "-- Select a Sub-server (optional) --"},
    { id: "509", text: "Subserver 509"},
    { id: "510", text: "Subserver 510"},
    { id: "511", text: "Subserver 511"},
]

This is the code I have built but I am missing something because the output is not as expected:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const values = "_/_-- Select a Sub-server (optional) --_|_509_,Subserver 509_|_510_,Subserver 510_|_511_Subserver 511";
const parts = values.split("_|_").filter(part => part.trim() !== "");
const arr = parts.map(part => {
    const [id, text] = part.split("_,");
    return { id: id || "", text: text || "" };
});

this is the result I got from my code:

console.log(arr);
[
  { id: '_/_-- Select a Sub-server (optional) --', text: '' },
  { id: '509', text: 'Subserver 509' },
  { id: '510', text: 'Subserver 510' },
  { id: '511_Subserver 511', text: '' }
]

Why are the first and last ids wrong and are missing the text value? Can I get some help identifying where is my issue?

Note: I am open to suggestions and improvements not tied to my code.

>Solution :

You don’t have _, separators in the first and last items, so you can’t use that as the delimiter between the ID and the value.

Also, you have _/_ before the first element, that won’t be removed by any of your code. You could use another regexp to treat that as a delimiter in the first split.

Since the comma is optional, you could use a regular expression as the delimiter: /_,?/ matches _ optionally followed by ,.

const values = "_/_-- Select a Sub-server (optional) --_|_509_,Subserver 509_|_510_,Subserver 510_|_511_Subserver 511";
const parts = values.split(/_\|_|_\//).filter(part => part.trim() !== "");
const arr = parts.map(part => {
    const [id, text] = part.split(/_,?/);
    return { id: id || "", text: text || "" };
});
console.log(arr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading