Add two conditions in filter Javascript

ぐ巨炮叔叔 提交于 2019-12-20 07:47:47

问题


Im trying to add two conditions in filter but only one works. The first condition check if it has empty spaces between words and the second condition if words.length is bigger than the given minimum length. if the string is "hello world" then i need to get when i split it ["hello", "world"]. Instead of that I am getting ["hello", "", "", "", "world"]

let wordsLength = sumOfSentence.split(" ");    
let longWords = wordsLength.filter(function(sumOfWord){
    //check if the words length is bigger than the minimum length
    //check if it has extra empty spaces
    if(sumOfWord !== "") return sumOfWord.length >= minLength
});

回答1:


Seems like you want to filter if sumOfWord is not empty and its length is greater than minLength. @Barmar suggests you the good solution, use the following code.

let wordsLength = sumOfSentence.split(" ");    
let longWords = wordsLength.filter(function(sumOfWord){
    return ((sumOfWord.trim() != '') && sumOfWord.length >= minLength)
});


来源:https://stackoverflow.com/questions/47083735/add-two-conditions-in-filter-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!