Skip to content
Advertisement

How to join strings conditionally without using let in javascript

I have a situation where I’m trying to join the array of strings only if it has a value. I did using let variable, but I wonder can I do this using map. I’m very mindful on the position, so I used in this way.

const [hours, minutes, seconds] =["", "10", ""]

  let time = "";

 if (hours) {
    time += `${hours}h `;
  }
  if (minutes) {
    time += `${minutes}m `;
  }
  if (seconds) {
    time += `${seconds}s`;
  }
  
  console.log(time)

Will I be able to do this using map, filter and join?

Advertisement

Answer

If you put the hours, minutes, and seconds back into an array, you can make another array for the suffixes, add the suffixes by mapping the values, then filter out the resulting substrings that are 1 character or less (which would indicate that there wasn’t a corresponding value).

const suffixes = ['h', 'm', 's'];
const [hours, minutes, seconds] = ["", "10", ""]; // combine this with the next line if you can
const hms = [hours, minutes, seconds];
const time = hms
  .map((value, i) => value + suffixes[i])
  .filter(substr => substr.length > 1)
  .join(' ');
console.log(time)
Advertisement