Home > Blockchain >  Best way of splitting a string and create the following array: '1-2-3' -> ['1'
Best way of splitting a string and create the following array: '1-2-3' -> ['1'

Time:10-19

the string is something like this:

const string = '1-2-3-4-5-6-7-...-n';

and I need an array like this:

const arr = ['1', '1-2', '1-2-3', '1-2-3-4', '1-2-...-n'];

I have go into this so far:

const str = '1-2-3'; 
const arr = []; let actualValue = '';
const splitArray = str.split('-');
for (let i = 0; i < splitArray.length; i  ) {
  if (actualValue)         
    actualValue = actualValue   '-'   splitArray[i];     
  else 
    actualValue = splitArray[i];
  
  arr.push(actualValue); 
}

CodePudding user response:

Maybe this solution will suit you?

const result = "1-2-3-4-5-6-7-8-9".split("-").reduce((prev, curr) => {
  const last = prev.slice(-1);
  last.push(curr);
  prev.push(last.join("-"));
  return prev;
}, []);
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I prefer

const str = '1-2-3'; 
const arr = []; let actualValue = '';
const splitArray = str.split('-');
if (splitArray.length) {
  actualValue = splitArray[0];
  arr.push(actualValue);
}

for (let i = 1; i < splitArray.length; i  ) {
  actualValue = actualValue   '-'   splitArray[i];
  
  arr.push(actualValue); 
}

console.log(arr);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

to reduce the number of comparisons.

CodePudding user response:

No splitting necessary, just a little arithmetic.

Here using String#slice() and a for loop with push()

const string = '1-2-3-4-5-6-7';

const result = [];
const len = Math.ceil(string.length / 2);

for (let i = 0; i < len; i  ) {
  result.push(string.slice(0, 2 * i   1));
}

console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

or with a while loop with unshift()

const string = '1-2-3-4-5-6-7';

let str = string;
let result = [];

while (str.length) {
  result.unshift(str);
  str = str.slice(0, -2);
}

console.log(result);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related