Trying to get length of array element

ive been trying to get my code to add all the even elements of an array to another array but it doesnt work. does anyone know why?

while (findEvenLengthStrings.length > i){

if (findEvenLengthStrings[i].length % 2 === 0){

newArray.push(findEvenLengthStrings[i]);

} else {

}
i++;

Why would you use a while instead of a for. I mean, filter would be cleanest, but for makes more sense than while.

And you are missing a closing bracket, yes? Do you initialize i? Or newArray? Can we see all of the code?

1 Like

I just fixed those problems and your code worked for me. Again, I think this is a messy way to do it (you also don’t need that else) but it can work.

this is it in total. items is an array and my code has too return all the even elements in that array


function findEvenLengthStrings(items) {

// Your code goes here...

var newArray = [ ];

for (var i = 0; i < findEvenLengthStrings.length; i++) {

if (findEvenLengthStrings[i].length % 2 === 0){

newArray.push(findEvenLengthStrings[i]);

}

}

return newArray;

}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

function findEvenLengthStrings(items) {
  // Your code goes here...
  var newArray = [ ]; // var is a legacy feature - const is better
  for (var /* use let here */ i = 0; i < findEvenLengthStrings.length; i++) {
    if (findEvenLengthStrings[i].length % 2 === 0) { // why are you trying to index into the function?
      newArray.push(findEvenLengthStrings[i]); // this isn't the name of the array of strings
    }
  }
  return newArray;
}
1 Like

Do you understand how function arguments work? If not, you may want to review that.

1 Like

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