Ayuda con loop for y busqueda en Array

Me estoy volviendo loco, estoy aprendiendo JS, aunque me cuesta, y me he propuesto hacer este ejercicio, pero fallo, y no se en que, me podríais ayudar? Gracias

var valores = [true, 5, false, "hola", "adios", 2];
function buscar () {
  let y = [];
  for(let lupa = 0; lupa < valores.length; lupa++){
    y.push(lupa);
  }
  valores += y;
}

Tengo que conseguir determinar cual de los dos elementos de texto es de mayor longitud.
Creo haber conseguido crear un for para utilizarlo de buscador y que incremento el número hasta máximo, la longitud del array.
Luego, quiero añadir esos números y utilizarlos como índices para buscar dentro del array, y con typeof string, identificar cuando encuentre una string

Luego, cuando las encuentre, hacer otra funcion o algo para cual sea más larga, se muestre por consola.

No se si me he liado, es mucho más simple que todo esto, pero estoy perdido…

Me estoy volviendo loco, estoy aprendiendo JS…

Yep, learning programming will do that to you. That is very normal.

Is this part of the curriculum? If so, please provide a link to it - we don’t have them memorized.

It’s not clear to me what you are trying to do.

I think I have managed to create a for to use as a search engine and that increased the number to the maximum, the length of the array.

I don’t see what search is happening here. For one thing, you don’t pass in a search parameter.

Then, I want to add those numbers and use them as indices to search inside the array, and with typeof string, identify when it finds a string

I don’t see how what you are doing is doing that.

I don’t know if I’ve gotten involved, it’s much simpler than all this, but I’m lost …

Perhaps, but sometimes that’s how we learn.


When I look at your code, this is what I see…

You have a global array valores (this should be passed in as a parameter). You create an array y. You push the indecies of the first array onto y. So, if there are 10 elements in valores you will end up with y being an array of 0 to 9.

Then you try to append the arrays (I guess) with this: +=. But that doesn’t work with arrays so JS is converting those arrays to strings (using their built in toString method) and so you are ending up with one big string.

I don’t think that is what you want. Perhaps it would be more clear if you explained on a higher level what you want. We can see what the input is, but what do you want the output to be? What do you expect valores to be after the function is run?

Muchas gracias por contestar y por tu tiempo. Me explico @kevinSmith .
Por cierto, es un ejercicio que he cogido pero no es de ninguna plataforma. Lo he buscado por Google, pero no tiene solución.
Ahora lo explico:
Tengo ese array con strings, números y booleanos.
En este ejercicio, lo que quiero es, conseguir crear una operación que identifique solamente las dos strings que hay, y que, de ellas dos, diga cuál es la que más caracteres o letras tiene (la strings más larga). Es decir, que por consola se muestre la string más larga.
Y para ello se me ha ocurrido hacer un for loop para buscar, seleccionar y separar las strings, con type of. Y una vez las tenga, hacer otra operación para compararlas y mostrar la string más larga, por consola.
El código no está acabado, porque no se me ocurre nada más sin acabar liandolo todo y estropeandolo.
Espero que me puedas o podáis ayudar.
Gracias

Por cierto, es un ejercicio que he cogido pero no es de ninguna plataforma. Lo he buscado por Google, pero no tiene solución.

OK, that’s cool.

OK, so you are looking for the longest string.

As I said, I would want to pass in the array instead of using a global variable.

As I understand, you want this function to display “adios” because that is the longest string in the array.

There are a couple of ways to do this. Of course a for loop is one. I don’t think you should have the array y. I think you should have a holding variable elMasLargo. You will store the current longest string, as you iterate, you will update that as needed. I would initialize it with an empty string. Then, as you iterate, you check if the current value is a string and if it is longer than what you have - if that is true, then we update elMasLargo. Then, after the loop, we return that value back.

Does that makes sense? Give that a shot and check back if you run into trouble.

Gracias de nuevo @kevinSmith
A ver, he estado probando y me ha salido esto:

var valores = [true, 5, false, "hola", "adios", 2];
let elMasLargo = "";

function buscar () {
  var y = [];
  for(let lupa = 0; lupa < valores.length; lupa++){
    y.push(lupa);
  }
  if(y == typeof string){
    console.log("true, is a string");
  } else {
    console.log("false, is not a string");
  }
}
console.log(buscar());

A que te refieres con; “holding variable”? a una variable global normal?

Igualmente estoy super atascado con todo esto, podrias mostrarme un ejemplo de como lo harías y yo intento hacer otro ejercicio parecido? No entiendo nada, ni me sale xD

A que te refieres con; “holding variable”?

I just meant a variable to store the current longest string, as you iterate through, it keeps track of the current “winner”. I would not make it global. Besides being a bad practice, it would mean that it would keep track of the longest strings from previous runs of the function. In general, global variables are a bad idea.

podrias mostrarme un ejemplo de como lo haría

I don’t want to give you the answer. I can try to explain in pseudo code what I think should happen.

Inside the function, I would expect to see:

initialize our holding variable as an empty string
loop over the array
  if the element is a string AND it is longer than the current longest string (the holding variable)
    then replace the current longest string with this element
  end loop
  return current longest string

That is what I would expect. And I would not expect any global variables. You can declare your valores variable in the global scope, but it shouldn’t be used globally - it should be passed into the function. There is no need for your y variable. I don’t understand what it is doing. The fact that you couldn’t come up with a good name implies that perhaps you aren’t sure what it is doing. Get rid of it. You don’t need an array, you just need the current longest string.

To start out, maybe just empty this function, then loop through console.log each element and see if it is a string. Then change the log to say (if it is a string) what is it’s length. Once you have that. See about storing the current longest string. Then you just have to return that.

1 Like

gracias, lo seguiré intentando, pero tendré que repasar más y practicar. Cualquier cosa, lo comento y te digo algo. Lo terminaré consiguiendo!

Cool. Like I said, break it into small steps. A bunch of small problems are exponentially easier to solve than one big problem.

1 Like

I think I’m close…

let palabras = '';
var valores = [true, 5, false, "hola", "adios", 2];

  function x1() {for(elementos1 of valores){
    if(typeof elementos1 === 'string'){
      palabras += `,${elementos1}`;
    } //IF.
  } //FOR.
} //x1().
x1()

let arr = palabras.split(',');
arr
function indexs(){
  for(let i = 0; i < arr.length; i++){
    console.log(`${arr[i]} have ${arr[i].length} letters`);
  } //FOR
} //indexs().
indexs()

SOLUTION

'hola have 4 letters'
'adios have 5 letters'

See about storing the current longest string. Then you just have to return that.

Me falta esto, sí

In general, global variables are a bad idea.

No se hacerlo sin variables globales

Please don’t take pictures of code. Please cut and paste the code in. It is a lot easier to help you that way.

1 Like

You’re right, sorry. Now is okey

OK, I guess I’m still confused about what you want this function to do. I thought we’d agree on one thing, but what you’re doing know is different.

So, if I have this:

var valores = [true, 5, false, "hola", "adios", 2];

var final = myFunction(valores);

console.log(final); // ???

What do you want the variable final to be. The longest string? An array of strings?

No se hacerlo sin variables globales

I don’t see anything requiring a global variable. I mean, you can store valores globally, but still pass it in as a parameter.

1 Like

What do you want the variable final to be. The longest string? An array of strings?

Exactly. I want the longest string.

OK, then let’s assume that you are doing this as an intermediary step, trying to get just a list a strings. I would rewrite what you have as:

const valores_global = [true, 5, false, "hola", "adios", 2];

function miFunction(valores) {
  const soloStrings = [];
  for (elemento of valores) {
    if (typeof elemento === "string") {
      soloStrings.push(elemento);
    }
  }
  
  console.log(soloStrings)
  
  const respuestaFinal = null;
  
  return respuestaFinal;
} 

const repuesta = miFunction(valores_global);

Then we just need to add in below the console.log, to get get the additional steps we need for a final answer.

Of course, that first step could be done with a filter method:

const soloStrings = valores.filter(el => typeof el === 'string')

For that matter, you can do this entire function in one line, but if it helps to learn, we can break it into pieces.

OK, so now you have a list of only strings. How do you find the longest one?

1 Like

De hecho, puede hacer toda esta función en una línea, pero si ayuda a aprender, podemos dividirla en pedazos.

Aún estoy aprendiendo ES6 poco a poco y no entiendo muy bien que sustituye la flecha =>…a function?
Vale, se que el método .filter crea un nuevo array con todos los elementos que cumplan la condición implementada por la función dada. Pero eso ya lo hice con if (typeof elemento === "string") { soloStrings.push(elemento); }
no?
O hay que hacerlo otra vez? Porque el array soloStrings no hace falta aplicar .filter... porque ya son strings, no?

Es decir, en que momento me estas diciendo que utilice .filter?

Bien, ahora tienes una lista de solo cadenas. ¿Cómo encuentras el más largo?

Con un método para comparar la longitud de todos los elementos del array soloStrings? Por ejemplo, restando la longitud máxima …ni idea. O utilizando una variable const con un número fijo, y la string.length que se acerque más a ese número, es la mas larga?


Tampoco entiendo muy bien la verdadera utilidad de asignar una función a una variable, como haces con const repuesta = miFunction(valores_global);?

Sorry, the “old” way of doing it would be:

const soloStrings = valores.filter(function(el) { return typeof el === 'string'; })

Pero eso ya lo hice con if (typeof elemento === "string") { soloStrings.push(elemento); }
no?

Yes, your method did the same thing. I was just showing a sleeker way to do it. But they do the same thing.

Or do we have to do it again? Because the soloStrings array does not need to apply .filter … because they are already strings, right?

No, I was showing two ways to do the same thing.

I mean, when are you telling me to use .filter?

No, just that that’s a slightly “better” solution. Don’t change it if you don’t understand it. Don’t worry about perfection - just solve the problem. We can worry about “best solution” later. I didn’t mean to throw you off. You can ignore my filter solution for now. In the real world, I would expect to see that. Or, more accurately, this entire function can be solved with a reduce method.

But for learning purposes, let’s solve this in pieces. You now have an array of only strings. (Regardless of which method you use to get it.) Now, how do we find the longest string. Again, the most obvious solution would be to use a for loop and have a variable where you store the current longest string. Imagine you have a list of 1000 random numbers and you want to find the largest. You go through the list one by one, and you have a white board where you write down the current largest number. When you start out, you just write down the first number - it is the current largest. Then you check the next number - if it is larger, you erase your whiteboard and write that down. Then you do that for the next number. You keep doing that until the list is done. When you’ve finished, whatever number is written on the whiteboard is the largest number. That is what we are doing here, basically.

There is also a “sexier” solution, using reduce, but if you are not comfortable with that, don’t worry about that for now. It is better to learn the for loop solutions first, then worry about the “sexy” solutions later.

So, see if you can build on what we have and figure out what the longest string is.

1 Like

Entendido, no pasa nada. Te lo agradezco, así me servirá para aprender en un futuro! También investigaré sobre el método .reduce, pero luego, como tú dices.

Vale, es un ejemplo super bueno, lo he entendido. Intento hacerlo y te digo.
Muchas gracias @kevinSmith , agradezco la ayuda porque no hay mucha gente que ayude tanto, como un tutor ! Estoy un poco bloqueado en JS pero poco a poco con esto veo un poco más la salida.
Vale, lo intento!

Yeah, JS is hard. It takes time.

I’m going to be moving to BCN in about a month, maybe I’ll see you around.

1 Like

Estoy intentandolo con `for (el of soloStrings){

console.log(el);
if(el.length >...........`

¡Anda!, si, 1 mes atrás entré en tu perfil por cotillear a más desarrolladores con experiencia y ver portafolios web, y me fijé que ponías Barcelona en tu Introducción, que casualidad, pensé!
Yo aquí estaré, aprendiendo más para desarrollar profesionalmente lo más pronto posible!
Claro que sí!

Yes, that can work. You need to have a variable to store the current longest string, like the whiteboard in my number example.

1 Like