Home > Software design >  How to combine 2 strings from an array if their length is shorter then x
How to combine 2 strings from an array if their length is shorter then x

Time:11-06

I am trying to combine words like "my", "I", "for" etc, with their neighbor word.

I was thinking that I may check each word's length and if it's shorter than 4 for example, join them with the next word.

Let's say I have the string 'about my projects': What I did was split it into a separate words like this

const words = string.split(" ");

Once I had the words I looped through them like this

    for (let i = 0; i <= words.length; i  ) {
      if (words[1   i].length <= 3) {
        const joinedWords = words[1]   " "   words[1   i];
        formattedWords.push(joinedWords);
      }
    }

The reason I used [1 i] is that I wanted the first word of the string to always be a separate word.

Unfortunately trying this does not work and the console throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'length')

Is there a way I could join words that are shorter than 4 characters with the next word like this?

input ['about', 'my', 'projects'];
output ['about', 'my projects'];
input ['something','for','something','for'];
output ['something'.'for something'.'for'];

CodePudding user response:

With for loop and continue to skip the iteration when matched condition

function combine(data){
  const res = [];
  let temp;
  for (let i = 0; i < data.length; i  ) {
    if (i === temp) continue;
    if (data[i].length < 4 && i !== data.length - 1) {
      res.push(data[i]   " "   data[i   1]);
      temp = i   1;
    } else {
      res.push(data[i]);
    }
  }
  return res;
}


console.log(combine(["about", "my", "projects"]));
console.log(combine(['something','for','something','for']));

CodePudding user response:

In this version I will continue to concatenate words, as long as they are shorter than 4 characters:

const wrds=['about','a','b','c','and','my', 'projects','and','other','hot','and','great','things'];

console.log(wrds.reduce((a,c,i,arr)=>{
 if (a.last) {
  a.last=a.last ' ' c;
  if (c.length>3){
   a.push(a.last);
   a.last=null;
  }
 }
 else if(c.length>3||i==arr.length-1){
  a.push(c);
 }
 else a.last=c;
 return a;
},[]));

CodePudding user response:

function joinWords(inp) {
  const res = []
  const arr = inp.split(' ')
  res.push(arr[0])
  let skipNext = false
  for (let i=1; i<=arr.length-1; i  ) {
    if(skipNext) {
      skipNext = true
      continue
    }
    if (i < arr.length-1 && arr[i].length <= 3) {
      const joined = arr[i]   " "   arr[i   1]
      res.push(joined)
      skipNext = true
    } else {
      res.push(arr[i])
    }
  }
  return res
}

console.log(joinWords('about my projects'))
console.log(joinWords('something for something for'))

  • Related