Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

  • 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading