Home > Enterprise >  Array items length is not working inside the function
Array items length is not working inside the function

Time:12-24

I want to filter an item and return only the longest word with out special characters (#$%^&*) but the length inside reduce function doesn't work.

//that what I tried
function LongestWord(sen) {
    let myarr = sen.match(/\w /gi);
    myarr.reduce(function(acc, curr) {
        return acc.length > curr.length;
    });
    return result;
}
LongestWord("i cant solve th%^*is");

CodePudding user response:

The reducing function should accumulate either the longest word, or just its length, in your case it accumulates a boolean (and tries to compare its length property, which for a boolean is simply undefined). That would be one way to do it:

function LongestWord2(sen) {
  const myarr = sen.match(/\w /gi);

  return myarr.reduce(function (acc, curr) {
    return Math.max(acc, curr.length)
  }, 0);
}

Or, without reduce, but map and Math.max instead:

function LongestWord3(sen) {
  const myarr = sen.match(/\w /gi);
  const lengths = myarr.map(word => word.length);
  return Math.max(...lengths);
}

CodePudding user response:

You need to return the word instead of a boolean value inside of reduce, beside the missing assignment or return of the result of reducing.

function longestWord(sen) {
    let myarr = sen.match(/\w /gi);
    return myarr.reduce(function(acc, curr) {
        return acc.length > curr.length ? acc : curr;
    });
}
console.log(longestWord("i cant solve th%^*is"));

  • Related