0

I'm trying to write a function that used reduce() method to count the number of items in an array and return the length of that array.

This is what I have so far:

function len(items) {
    items.reduce(function(prev, curr, index){
        return index+1;
    });
}

let nums = [1, 2, 3];

console.log(len(nums));

Whenever I try to run this code, in the console on my browser I get the message 'undefined'. I think I defined my function properly, so I don't know why its not being called or outputting any values. Please let me know what I'm doing wrong or if my logic is wrong.

3 Answers 3

2

You forgot to return

function len(items) {
    return items.reduce(function(prev, curr, index){
        return index+1;
    });
}

or simply

function len(items) {
    return items.length;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I need to use reduce in order to get the length.
@flamedra then you can choose first option I have mentioned.
2

function len(items) {
    return items.reduce(function(prev, curr, index){
        return index+1;
    });
}

let nums = [1, 2, 3];

console.log(len(nums));

1 Comment

This is working. Can you please explain whey I need to return both the reduce method when I'm also returning inside the function?
0

try this :

function len(items) {
  if(items){                 //error handle
    return items.length;

  }
       return 0;
}

2 Comments

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
I need to use the reduce method to get the length.

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.