Kelajatu
Kelajatu

Reputation: 11

Return an array with the length property of arguments passes

Currently Stuck on this challenges.

// stringLengths takes in four strings
// it returns an array containing the length of each string
// Example: stringLengths('mushroom', 'onion', '', 'garlic') returns [8, 5, 0, 6] 

function stringLengths(str1, str2, str3, str4) {

}

Curently have

function stringLengths(str1, str2, str3, str4) {
    var arr = [];
    for (var i = 1; i < arguments.length; i++) {
        arr.push(arguments[i].length);
    }

    return arr;
}

This return me an empty array.

How can I push the length property of of each arguments into the Array and return the array with the lengths of each?

Upvotes: 1

Views: 2177

Answers (5)

Fabio Lolli
Fabio Lolli

Reputation: 889

If you just want an array of the lengths:

function stringLengths(str1, str2, str3, str4) {
  return Array.from(arguments).map((x) => x.length);
}

Should do the trick

Upvotes: 4

Ele
Ele

Reputation: 33736

Using the implicit object arguments you can get the keys, check for the attr length if a passed object doesn't have that attr.

const stringLengths = function() {
  return Object.keys(arguments).map(k => arguments[k].length || 0);
}

console.log(stringLengths('ele', 'from', 'stackoverflow', 2222));

Upvotes: 0

Orelsanpls
Orelsanpls

Reputation: 23565

You can use of ... and Array.map which are ES6 features. So you will handle any number of string.

function stringLengths(...args) {
  return args.map(x => x.length);
}

console.log(stringLengths(
  'str1',
  'je suis un chocolat',
  'les croissants sont bons',
));


More concise

const stringLengths = (...args) => args.map(x => x.length);

console.log(stringLengths(
  'str1',
  'je suis un chocolat',
  'les croissants sont bons',
));

Upvotes: 6

Guillaume Georges
Guillaume Georges

Reputation: 4020

Your code works fine. You just need to start your loop with i=0 instead of 1, if you want all your arguments lengths.

function stringLengths(str1, str2, str3, str4) {
  var arr = [];
  for (var i = 0; i < arguments.length; i++) {
    arr.push(arguments[i].length);
  }

  return arr;
}

console.log(stringLengths("hello", "okay", "doh"));

Upvotes: 2

Nope
Nope

Reputation: 22339

Your code is working fine, except you are starting at 1 instead of index 0. Arrays have a zero based index, hence I when you pass only 1 argument you get the initial empty array as the loop is not executed at all.

function stringLengths(str1, str2, str3, str4) {
  var arr = [];
  for (var i = 0; i < arguments.length; i++) {
    arr.push(arguments[i].length);
  }

  return arr;
}

var x = stringLengths('123', '123456789', '12345');
console.log(x);

More Details on accessing array elements here

Upvotes: 3

Related Questions