Skip to content
Advertisement

Splitting string into array based on first and last

I have this array :-

var a = [‘ DL1,C1,C5,C6′,’M4,DL3-7,B1-5’]

And I want to split them like

[DL1,C1,C5,C6,M4,DL3,DL4,DL5,DL6,DL7,B1,B2,B3,B4,B5]

So that DL3-7 or DL3-DL7 this Split like this DL3,DL4,DL5,DL6,DL7

Reason why I am doing this, is because I want to block duplicate entry like DL3 should not come anywhere else, I am trying for loops to do this, just want to know if there is any simpler way to do it, and check for duplicacy afterwards.

Thanks

Advertisement

Answer

Create an Array with that length, iterate and transform, I’ve just wrote the most challenged part:

function splitRange(range) {
  let a = range.split('-');
  if (a.length < 2) return [range];
  const baseString = (a[0].match(/[a-z A-Z]/g))?.join('');
  const baseNumber = +((a[0].match(/d+/))?.shift());
  return Array.from({length: +a.pop().match(/d+/) - baseNumber + 1}).map((_,i)=>`${baseString}${i+baseNumber}`);
}

const s='DL1,C1,C5,C6,M4,DL3-7,B1-5';

console.log(
  s.split(',').map(item=>splitRange(item)).flat()
);
Advertisement