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

160
Views
join list elements if their length doesn't exceed a max character limit

so I have a list var be = ["Hello", "welcome", "Hi", "morning", "Hi"] and I want to join the strings if the final string doesn't exceed 12.

so the final result must be a list: ["Hello--welcome", "Hi--morning--Hi"] // I need the -- included

I tried using regex by joining them into one big string and then using .match but didn't work.

EDIT:

this is what I tried:

var s = ["Hello", "welcome", "Hi", "morning", "Hi"].join("--")
var result = s.match(/.{1,12}/g) // ['Hello--welco', 'me--Hi--morn', 'ing--Hi']

thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  • Using Array#reduce, iterate over the array while updating a list of objects with words array and total (total length of words). At each iteration, check if adding the current string to the last added object would exceed a "MAX_LENGTH", if it doesn't update it, otherwise add a new object
  • Using Array#map and Array#join, return the joined list of words

const 
  arr = ["Hello", "welcome", "Hi", "morning", "Hi"],
  MAX_LENGTH = 12;

const res = 
  arr.reduce((list, str) => {
    const last = list[list.length-1];
    if(last && last.total + str.length <= MAX_LENGTH) {
      last.total += str.length;
      last.words.push(str);
    } else {
      list.push({ total: str.length, words: [str] });
    }
    return list;
  }, [])
  .map(({ words }) => words.join('--'));

console.log(res);

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!