• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

107
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

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

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error