最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

if statement - Javascript: Finding the longest name from an array - Stack Overflow

programmeradmin1浏览0评论

I am trying to learn javascript and am just beginning.

So I have created my own project. I have an array of Rivers and want to pare the lengths of their names.

I know it IS NOT written in code form - since I am beginning - I like to write in english what I have to do.

I'm not sure how to set up the if/else statements with this large a parison.

Can anyone help with Step 3 by pointing me in the right direction without spoonfeeding me an answer?

Thanks!

STEP 1 - List River names
STEP 2 - List River names lengths
STEP 3 - List the longest River and list the # of letters in the name
STEP 4 - List the Shortest River and list # of letters
STEP 5 - List the number of letters difference between the longest and the shortest ~ Modulo

/STEP 1/ - Done

var rivers = ["Mississippi","Delaware","Ohio","Sangamon","Black","Current","Chattahochee"];

for (var i = 0; i < rivers.length; i++) {
    console.log("An interesting "+rivers[i]+" River fact:")
    ;



/STEP 2/ - Done

  console.log("The "+rivers[i]+" River's name contains "+ (rivers[i].length)+" letters in it.")
    ;
}

/STEP 3/ HERE I want to pare the letter strings to find the longest name in the array. I then want the output to say “The river with the longest name is the X River, and it has Y letters." But I do not understand how to set up the if-else statement.

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


If A.length > B.length Keep A else keep B

If A.length > C.length Keep A else keep C
If B.length > C.length Keep B else keep C

If A.length > D.length Keep A else keep D
If B.length > D.length Keep B else keep D
If C.length > D.length Keep C else keep D

If A.length > E.length Keep A else keep E
If B.length > E.length Keep B else keep E
If C.length > E.length Keep C else keep E
If D.length > E.length Keep D else keep E

If A.length > F.length Keep A else keep F
If B.length > F.length Keep B else keep F
If C.length > F.length Keep C else keep F
If D.length > F.length Keep D else keep F
If E.length > F.length Keep E else keep F

If A.length > G.length Keep A else keep G
If B.length > G.length Keep B else keep G
If C.length > G.length Keep C else keep G
If D.length > G.length Keep D else keep G
If E.length > G.length Keep E else keep G
If F.length > G.length Keep F else keep G

I am trying to learn javascript and am just beginning.

So I have created my own project. I have an array of Rivers and want to pare the lengths of their names.

I know it IS NOT written in code form - since I am beginning - I like to write in english what I have to do.

I'm not sure how to set up the if/else statements with this large a parison.

Can anyone help with Step 3 by pointing me in the right direction without spoonfeeding me an answer?

Thanks!

STEP 1 - List River names
STEP 2 - List River names lengths
STEP 3 - List the longest River and list the # of letters in the name
STEP 4 - List the Shortest River and list # of letters
STEP 5 - List the number of letters difference between the longest and the shortest ~ Modulo

/STEP 1/ - Done

var rivers = ["Mississippi","Delaware","Ohio","Sangamon","Black","Current","Chattahochee"];

for (var i = 0; i < rivers.length; i++) {
    console.log("An interesting "+rivers[i]+" River fact:")
    ;



/STEP 2/ - Done

  console.log("The "+rivers[i]+" River's name contains "+ (rivers[i].length)+" letters in it.")
    ;
}

/STEP 3/ HERE I want to pare the letter strings to find the longest name in the array. I then want the output to say “The river with the longest name is the X River, and it has Y letters." But I do not understand how to set up the if-else statement.

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


If A.length > B.length Keep A else keep B

If A.length > C.length Keep A else keep C
If B.length > C.length Keep B else keep C

If A.length > D.length Keep A else keep D
If B.length > D.length Keep B else keep D
If C.length > D.length Keep C else keep D

If A.length > E.length Keep A else keep E
If B.length > E.length Keep B else keep E
If C.length > E.length Keep C else keep E
If D.length > E.length Keep D else keep E

If A.length > F.length Keep A else keep F
If B.length > F.length Keep B else keep F
If C.length > F.length Keep C else keep F
If D.length > F.length Keep D else keep F
If E.length > F.length Keep E else keep F

If A.length > G.length Keep A else keep G
If B.length > G.length Keep B else keep G
If C.length > G.length Keep C else keep G
If D.length > G.length Keep D else keep G
If E.length > G.length Keep E else keep G
If F.length > G.length Keep F else keep G
Share Improve this question asked Sep 9, 2015 at 19:55 Thomas GrieveThomas Grieve 231 silver badge4 bronze badges 1
  • 7 Instead of thinking in terms of all those different variables, think about "biggest one I've seen so far" and "the one I'm looking at now". – Pointy Commented Sep 9, 2015 at 20:02
Add a ment  | 

9 Answers 9

Reset to default 2

You're on the right track, but you're overthinking this; just keep track of the longest one when you're looping. If you find one that's longer, update it. I'll even psuedocode this for you so you can see:

myfunc() {
    var longest = "";
    for <all your things> {
        if <thing>.length > longest {
            longest = thing
        }
    }
    //longest contains our longest thing!
    //you can get the length by doing longest.length
}

Sort the list of rivers from the shortest to the longest:

rivers.sort(function(a, b) {
    return a.length - b.length;
});

Then the shortest is rivers[0] and the longest is rivers[length - 1].

This is not the ideal solution, but it's good enough for learning.

You could use reduce. It allows you to iterate through an array and carry a value from the previous iteration to the next. You can use that ability to store the longest name, and replacing it when you e across an even longer name.

var longestName = rivers.reduce(function(longName, maybeLongerName){
  // What you return here, bees "longName" in the next iteration
  // If it's the last item, what you return is the value returned by reduce
  return maybeLongerName.length > longName.length ? maybeLongerName : longName; 
}, '');

Use two variables. One holds the longest length of a name, the other holds the index in the array. As you loop through the array, pare the length of the current element with the longest name.

var longest_length = -1;
var longest_index = null;
for (var i = 0; i < rivers.length; i++) {
    if (rivers.length[i].length > longest_length) {
        longest_length = rivers.length[i].length;
        longest_index = i;
    }
}
console.log("The " + rivers[longest_index] + " river's name contains " + longest_length + " letters");

you should create a block of code that iterates through the array paring 2 values. For example

var index = 0;
var length = 0;
var name = "";
for(var i = 0; i < rivers.length; i++){
    if(rivers[i].length > length){
        length = rivers[i].length;
        index = i;
        name = rivers[i];
    }
}

Then you can return that info.

+1 @Pointy 's ment.

@Joseph the Dreamer 's answer is a very good one (the best?), but for a beginner it may be a little plex.

Think back to Pointy's ment. How would you do that? A loop. What else would you need? A stored value. And, finally, you would need to pare the length of the stored value vs the current value in the loop, and update the stored value if the current value is longer.

Now, Joseph's reduce answer pretty much does exactly that, but very elegantly (usually harder to understand unless you're used to it). Try to acplish this with a basic for loop first. When you "get" the loop, you'll better understand the reduce solution (also, you may need to read up on conditional ternary operators to better understand the reduce solution).

Spoiler: http://jsfiddle/v7wvg7ns/

(I can't just link the fiddle without some code, so here's some code)

// Ignore this
 function longFriend(arr){
            var long = arr[0];
             for (let i = 0; i < arr.length; i++) {
                const element = arr[i];
                    if( long.length < element.length){
                        long = element
                        }
                             }
                            return long
                                }

                var  friend = ["abir","abdullah","robin","abdurrohim","ali"]
                var longword = longFriend(friend)
                console.log(longword)
const names = ['John Michael Doe', 'Laurain', 'Smith', 'Jamie Neesham'];
const namesObject = names.reduce((prev, current) => {
  prev[current.length] = current;
  return prev;
}, {});
const index = Object.keys(namesObject)
  .sort((a, b) => a - b)
  .pop();
const longestName = namesObject[index];

console.log(namesObject);

You can do something like this.

 var amountOfLetters = 0;
 var indexOfLongestName = 0;
        for(var i = 0; i < rivers.length; i++){
            if(rivers[i].length > amountOfLetters){
                amountOfLetters = rivers[i].length;
                indexOfLongestName = i;
            }
        }
发布评论

评论列表(0)

  1. 暂无评论