Home > Blockchain >  join list elements if their length doesn't exceed a max character limit
join list elements if their length doesn't exceed a max character limit

Time:11-21

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

CodePudding user response:

  • 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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related