Devin Miller
Devin Miller

Reputation: 179

javascript reduce in function

I am brand new to javascript and have only an entry level java college course under my belt. I am taking a course online to learn JS and have run into a hiccup. I am supposed to create a function that parses a string and finds the longest word. I figured the problem out, but could not understand why the following function was giving me an undefined. Any help would be great as I try to deeper my understanding of the language.

var statement = 'This is an example string'
//undefined

var result = statement.split(' ').reduce(function(acc, cur) {
  if (acc.length > cur.length) {
    return acc;
  } else {
    return cur;
  }
});

console.log(result);  //"example"

function longest(string) {
  string.split(' ').reduce(function(acc, cur) {
    if (acc.length > cur.length) {
      return acc;
    } else {
      return cur;
    }
  });
}

result = longest(statement);
console.log(result);  //undefined

Upvotes: 1

Views: 632

Answers (4)

YTScorpion
YTScorpion

Reputation: 31

You are not returning a value from your function. There are special types of functions called Arrow Functions in JavaScript which let you avoid using the return statement. It works only for one-line statements, though. More on arrow functions can be found here.

Here's how my solution would look like:

const statement = 'This is an example string';
const longest = string => 
  string.split(' ').reduce((acc, cur) => acc.length > cur.length? acc: cur);
console.log(longest(statement));

Upvotes: 0

Akrion
Akrion

Reputation: 18525

Another simple way to achieve the same result would be to to split the array into words and then simply sort it in descending order by word length ... then just pick the first element.

var statement = 'This is an example string'
var result = statement.split(' ').sort((x,y) => y.length - x.length)[0]

console.log(result)

Upvotes: 0

Nithya Rajan
Nithya Rajan

Reputation: 4884

Your function should return something. If you don't 'return' any values in JavaScript, it will return 'undefined'

In your problem, your function has a reduce method which returns a value inside your 'longest' function. But, the 'longest' function should return the value. So that the value will be available when u invoke this function

function longest(string){ 
   return string.split('').reduce(function(acc,cur){
       if (acc.length > cur.length){
          return acc;
       } else { 
          return cur; 
       } 
   }); 
 }

Upvotes: 1

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4925

Need to add a return from the function.

var statement = 'This is an example string'
//undefined

function longest(string) {
  var result = string.split(' ').reduce(function(acc, cur) {
    if (acc.length > cur.length) {
      return acc;
    } else {
      return cur;
    }
  });
  return result;
}

result = longest(statement);
console.log(result);

Upvotes: 0

Related Questions