简体   繁体   中英

Javascript: Finding the longest name from an array

I am trying to learn javascript and am just beginning.

I have an array of Rivers and want to compare the lengths of their names.


STEP 2 - List River names lengths
STEP 3 - List the longest River and list the # of letters in the name<\/strong>
<\/strong>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


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:")
    ;

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'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
}

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 come across an even longer name.

var longestName = rivers.reduce(function(longName, maybeLongerName){
  // What you return here, becomes "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, compare 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 comparing 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 comment.

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

Think back to Pointy's comment. How would you do that? A loop. What else would you need? A stored value. And, finally, you would need to compare 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 accomplish 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.net/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;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM