Home > Blockchain >  How to join strings conditionally without using let in javascript
How to join strings conditionally without using let in javascript

Time:07-13

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?

CodePudding user response:

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)

CodePudding user response:

Here's a nice little snippet

const suffixs = "hms"; // String arrays of single characters can be shortened to this!
const values = ["","10",""];

var string = values
               .map((x,i) => x ? x   suffixs[i] : x)
               .filter(x => x)
               .join(" ");
           
console.log(string);

// Or if you want to have 0 in place of empty values

var string2 = values
                .map((x,i) => (x || "0")   suffixs[i])
                .join(" ");

console.log(string2);

CodePudding user response:

Personally, I would create a list of objects, that represents the time.

I prefer this over using two arrays, as it can save some bugs (like changing the order of the data in one list but not in the other one):

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

const time = [
  { amount: hours, sign: "h" },
  { amount: minutes, sign: "m" },
  { amount: seconds, sign: "s" },
];

const str = time
  .map((val) => (val.amount ? val.amount   val.sign : ""))
  .join(" ")
  .trim();

console.log(str);

  • Related