Function with array as parameter

Hi everyone,

I am trying to write a function which takes an array and returns a new array with the number of characters in each string from the original array, but it is not working.

Only the number of characters of the first string is returned. I am almost sure that this is because the parameter suggests that there is only parameter, rather than an array of parameters, but I am not sure how this should be represented as this is how the original problem was set up and presented to me. I hope someone knows what I mean (!). I am still pretty new to this, so sorry if it seems like it should be obvious…

Could someone offer help?

function sortByLength(array) {
  let i;
  let tempArray = [];
  for (i = 0; i < array.length; i++) {
    tempArray.push(array[i]).length;
  }
  return tempArray;
}

what do you want the length of?

I want to push the lengths of each string in the original array into the new array…

e.g. [‘dog’, ‘cat’, 'mouse} —> [3, 3, 5]

without push, how do you get the length of array[i]?

function sortByLength(array) {
 return array.map(item => item.length).sort();
}

Not sure if you actually want the sorting in the end, but based it on your function name

1 Like

is it ‘array[i].length’?

1 Like

exactly, so if you want to push that, you want to put that all as an argument for push, look at your code

ok, thank you. This is now pushing a result I also did not expect:

it’s returning the number of characters at array[0], followed by say [1,1,1,1,1] of the length of array[0] is five…

any ideas?

show your code 

function sortByLength(array) {
  let i;
  let tempArray = [];
  for (i = 0; i < array.length; i++) {
    tempArray.push(array[i].length);
  }
  return tempArray;
}

console.log(sortByLength("dfdww", "scvx"));

You aren’t passing an array to your function

I am thinking the way the parameter is written may be a problem?

Not in array format?

yes, sorry. I am trying to solve a problem that was presented to me in this way, so I assumed (wrongly) that the parameter format was correct. Just need to figure out how to set an array as the parameter in a function then…I will try to find out

Ah, so the calling convention is given to you?

Take a look at this

yes, it’s given, so I presumed it should be left as is…

thanks for the link, I will take a read and see if I can fix it…

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.