Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

77
Views
Best way of splitting a string and create the following array: '1-2-3' -> ['1', '1-2', '1-2-3']

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); 
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

to reduce the number of comparisons.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!