Return the index of the largest element in an array

Asked

Viewed 1,553 times

4

I’m trying to return the higher index of the vector, I made the following code but returns undefined in function:

let array = [2, 3, 6, 7, 10, 1];
function retornaMaiorIndice(){
    for (let i = 0; i <= array  ; i++){
        var maior = 0;
        let atual = array[i];
        if (array[i] > atual) {
            maior = array[i];
        }
    } 
    return maior;
}

console.log(retornaMaiorIndice(array));

  • is not array.length has several problems

  • 3

    Catch the biggest Dice or catch the biggest Value?

  • I wanted to get the highest index, the position say, has the vector for example [0, 1, 2], I wanted it to return the index 2 that would be the highest.

  • @Saul44 If the array is [10, 20, 30], the largest element is 30 and the highest element index is 2. Which of these results do you want? (in his example it was not clear why the indices are equal to the values)

  • As I said, Indice is one thing, value is another, by your example you want the highest value, Indice is something else.

  • @hkotsubo I want the content of the largest element please excuse me I formulated my question incorrectly.

  • 2

    @Saul44 the Dice of this array [10, 30, 400] are 0, 1 and 2 ... the values are 10, 30, 400, the value 10 is in Dice 0, the value 30 is in Dice 1 and the value 400 in Dice 3. Comprises?

  • So 10 is at 0, 30 at 1, and 400 at 2, wouldn’t that be it? @Guilhermenascimento ?

  • That Saul, then the title of the question speaks take the biggest Dice, but the answers return you the greatest value, there is the doubt, you want to take the biggest Dice (from 0 to 5 in your example, the result would be 5) or you want to take the Dice whose value is the highest (in your example the Dice with the highest value is the Dice 4, which has the value 10) or you want to actually get the highest value (which has nothing to do with indices)?

  • I want to take the index, in a vector with 5 elements for example, return the value 4, since it goes from 0 to 4.

  • @Saul44 I think I got it, but this definition I just gave is very ambiguous yet.

  • You understood my question, there were 3 situations, the Dice falls into two, two are about taking Dice, what changes is the condition to catch such Dice, then I repeat again: You want to take the Dice with the highest VALUE (in YOUR example [2, 3, 6, 7, 10, 1] the highest value Index is the 4, for the value is 10)? Or actually take the "biggest" Dice (which in your case is the last ever [2, 3, 6, 7, 10, 1], in this case SPECIFIC would suffice let array = [2, 3, 6, 7, 10, 1]; let maior = array.length - 1; console.log(maior);)? Which of the two?

  • The highest value in the case of what returns with array.lenght -1, that’s right. In the case you said it would be 4.

  • Thank you, I expressed myself badly, I will endeavor to in the next doubt explain in an understandable way.

Show 9 more comments

3 answers

17


After many comments, the problem was up to another. As the question had repercussion I will try to give an answer that is what you need.

Need to synchronize the index that is along with the highest value found in another variable, because it is data that needs to be maintained and walk together.

function retornaIndiceMaiorValor() {
    let maior = array[0];
    let indice = 0;
    for (let i = 1; i < array.length; i++) {
        if (array[i] > maior) {
            maior = array[i];
            indice = i;
        }
    }
    return indice;
}

let array = [2, 3, 6, 7, 10, 1];
console.log(retornaIndiceMaiorValor(array));

I put in the Github for future reference.

Note that you can find the index after knowing which is the highest with indexOf(), but then I think it would only be worth it if I used the max() to find the biggest.

To learn the basic errors you had in the original code is the answer below. The question borders to be off topic because he was in need of what he actually needed, he’s the one XY problem, if it is to answer completely, the doubt was about the undefined.


The code makes no sense and has several errors.

  • The variable initialization must be outside the loop, otherwise the largest will always be 0.
  • You must close the loop until i enough in the size of array, and not if iis smaller than thearray, which is not a number, is a complex object with multiple data inside, so take the right property.
  • And it should close before it reaches the end because the array starts at zero, it cannot pick up the index that is equal to the size because this index does not exist, it is like having 10 digits, goes from 0 to 9, there is no 10.
  • There compares to array[i] is greater than array[i], what is obviously not since it is equal, has no different, perhaps the creation of the unnecessary variable has confused. Interestingly writing right you can read easy because you have to buy with maior even.
  • I used 0 to stay in the original rule, but if I allowed negative values then I would have to take the lowest possible negative value or start by taking an initial element to compare. This code works for these numbers, not as a general rule.
  • I changed the name of the function to indicate clearly what it does, if I wanted to return the index of the highest value then the name should be retornaIndiceMaiorValor() and then the logic would be different because it would have to control which is the index of the highest value also.
  • The rest I improved to simplify and organize.

function retornaMaiorValor() {
    var maior = 0;
    for (let i = 0; i < array.length; i++) if (array[i] > maior) maior = array[i];
    return maior;
}

let array = [2, 3, 6, 7, 10, 1];
console.log(retornaMaiorValor(array));

I put in the Github for future reference.

I considered that this is a case where the person is learning to do so, it is a coding exercise, and as it has several problems in the code it would be important to show how to do the same code, but correctly. In codes in production a simpler and more ready code is more interesting, Augusto demonstrated this form.

  • 5

    Yet another senseless negative given by those who only want to disrupt. Note that I do not complain of negative that you can see that there may be something, that was from a user who may not have liked something punctually, but always given by person who wants to show that will punish me every time she gets displeased with something that has nothing to do with the answer is hard to swallow. In fact mine even points out all the mistakes, even the smallest.

  • This code is very good!! And instead of 0 it is possible to put another value that javascript allows! Which is Infinity, only instead of just putting Infinity, put the higher value as -Infinity. Thus, any value within the vector will be greater than -Infinity, and therefore the first element of the vector, even if negative, will already be considered as the largest element of the vector!

  • @Leonardooliveira in fact the infinite could only be used, and it would even be the case to use even if you wanted to find the smallest.

  • yes, I know! But as in case he wants to find the biggest, then the Infinity can not be used.

  • 4

    If it is a continued negativity has to be punished. Vote because you disagree or vote because you agree with content, but don’t vote for problems,

  • 1

    @Augustovasques yes, it is more or less like this, of course the person does not leave negatively without stopping, he knows how to deal with the system’s limit, but I can not do anything to not appear that the persecution is mine. Note that it is a different person from yesterday :D The 2 today compete to see that it is the biggest negativator on top of me, and they do not negatively so many other people (one of them even negatively other 2 abastante, but has not done more), the system does not look at these nuances. Do not look that after a bullshit the person changed the voting pattern and went from positive to negative almost 100%.

  • @Maniero I just gave a positive vote, I’m learning, yesterday when I did this code nor did I get to analyze right out of tiredness, thank you very much for answering my question, very well detailed the answer but could indicate me how I would return the highest index when I say this I speak of the position in the array, example: [0, 1, 2] I wanted the value 2, because the vector starts at 0 as you said. Thank you very much in advance.

  • @Saul44 Note that people voted to close your question because it is not clear. I initially thought it was clear, but more and more it seems that it is not. When you are going to solve a problem the first thing you need to do is to know all the necessary details and use the correct terms mainly to talk to other people. If you can’t do that, you need to learn first, because that’s gonna be missed your whole life. Value and index are different things, so far it is not clear which of the two wishes,

  • Even in the comment now you can’t know which of the two you want, because the value and the index are equal in this example. So without a very clear question, it’s hard to get a straight answer. And I don’t know if it’s much use to tidy up now because of the answers already given on top of what you’ve come to understand, and already very positive.

  • @Maniero the position of the value of the vector, in the case of the largest, [20, 30, 40], respectively 20 occupies 0, 30 occupies 1, and 40 occupies 2, I wanted to return to the highest position in this case 2, I expressed myself correctly now?

  • Now yes, in this example, you have managed to explain yourself. You want the index of the largest element in the list. Several implementations of search arrays return -1 to indicate that it was not possible to find the element in question (this would only be in the case of an empty list, but has other uses in general searches, such as searching for the element 100 inside [20, 30, 40])

  • @Saul44 It seems that you really want the index, but it is still not totally clear, because it is in ascending order and it could be coincidence, I understood what I understood, but I had found it before and I made a mistake. If you say come in [10, 40, 20, 30] Whether the result is 1, bearing the index of where is the highest value of the list, there seems to be more clear. This was even said in the question, but the code indicated something else. However, are you sure you want this? It usually makes little sense to need that information.

Show 7 more comments

14

To find the highest value within a vector you can use the method Math.max() which returns the greater of one or more numbers:

var lista = [2, 3, 6, 7, 10, 1];
console.log(Math.max.apply(null, lista));

Also possible to do the same code using the scattering syntax that allows an iterable object to be expanded to be used where zero or more arguments are expected:

var lista = [2, 3, 6, 7, 10, 1];
console.log(Math.max(...lista));

  • 1

    And if the list is empty, the answer is what?

  • 1

    @Jeffersonquesado ai makes an if before executing :P (is a suggestion): console.log(lista.length ? Math.max.apply(null, lista) : 0); or if (lista.length) { return Math.max.apply(null, lista); } else { return 0; } if it is to return in a function and have something else to apply

  • Both, questioning and response, are useful and interesting.

  • @Guilhermenascimento was more of a curiosity. I’m not used to JS, but in other corners that offer similar things, it has a default return value or even something like a monad to indicate that "there was no return" (like the IntStream.max java)

  • @Jeffersonquesado, perfect! You really have to be asked. As Cool put in his answer is a production code and person has to get out of here knowing what the obstacles.

  • 2

    @Jeffersonquesado mas esta correta em questionar, in JS returns -Infinity if I am not mistaken, what is probably not expected, by the AP code returns "zero", so I adjusted the first comment with the suggestion. I personally think that we do not need to solve everything in "minimalism", I know that Augusto understands well the logic of programming, but I see many users here on the site asking that they do not even know how to use IF, ELSE, ||, && and when they come across simple things they think everything can be avoided "logic"

  • 1

    Augusto, I edited the first comment with the suggestion. Although I still questioned the AP: https://answall.com/questions/436409/return-o-maior-element-de-um-array#comment843839_436409

  • 1

    Yes: https://ideone.com/0GhUdi has to make a guard, or rather if it is empty and not try or after if it comes back this

  • 2

    Your answer shows a better way to get the bigger one, but does it help to clear the question? Maybe whoever asked the question doesn’t know what’s wrong and just copies the code and paste it to resolve a situation ;)

  • @Ricardopunctual, perfect. I understand and accept the orientation.

Show 5 more comments

9

Your code has several problems:

  • in the for to know the size of the array you need to use array.length:
  • you need to start the larger variable just before starting the for;
  • you need to see if the current value is greater than the variable maior and not atual.

See how you got these fixes:

let array = [2, 3, 6, 7, 10, 1];
function retornaMaiorIndice() {
    var maior = array[0]
    // iniciando o for com o elemento da posicao 1, pois o maior já é, temporariamente, o da posicao 0
    for (let i = 1; i < array.length; i++){
        if (array[i] > maior) {
            maior = array[i];
        }
    } 
    return maior;
}

console.log(retornaMaiorIndice());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.