1

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?

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Lovely. This helps
1

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);

Comments

-2

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
  .filter((val) => val.amount)
  .map((val) => val.amount + val.sign)
  .join(" ");

console.log(str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.