Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the sum of the lengths of all arrays?

I receive different strings as arguments, there may be several of them.
I check in the if block if there are more than 1 argument, then I need to return the sum of the lengths of the lines that were passed in the function arguments. How can i do this?

const strSum = (...args) => {
  let sum = 0;
  if (args.length > 1) {
    args.forEach((item) => {

    });
  }
  return sum;
};

console.log(strSum('hello', 'hi', 'my name', 'is')); //16

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can add item.length to the sum. item.length will be equals to the length of the string.

const strSum = (...args) => {
  let sum = 0;
  if (args.length > 1) {
    args.forEach((item) => {
      sum += item.length
    });
  }
  return sum;
};

console.log(strSum('hello', 'hi', 'my name', 'is')); //16
console.log(strSum()); //0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading