Ayuda con loop for y busqueda en Array

Hi, good afternoon.
No se de que manera sustituir/borrar los valores anteriores cuando sale un numero grande.
Puedes ser con .replaceAll? con respuestaFinal[i-1]?

De momento ayer conseguí separar las strings con el bucle for…of

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);
    }//IF.
  }//FOR-1.
  console.log(soloStrings)
  const respuestaFinal = [];
  for (el of soloStrings){
    respuestaFinal.push(el);
    console.log(respuestaFinal);
    }//FOR-2.
}//Function.
  
const repuesta = miFunction(valores_global);

Y, porque pusiste el parámetro valores en la función function miFunction(valores)?
No es lo mismo quevalores_global no?

  const respuestaFinal = [];
  for (el of soloStrings){
    respuestaFinal.push(el);
    console.log(respuestaFinal);
    }

All this is doing is making a copy of the soloStrings array. And we don’t need repuestaFinal to be an array. We just need a string.

You still seem to not understand what I mean by a holding variable. Let me try an example in code. I gave an example earlier about finding the largest of a list of numbers.

const NUMS = [65, 3, 67, 2, 39, 32, 6, -5, 127, 0, 93]

function getLargestNumber(numbers) {
  let biggestNumber = null
  for (let n of numbers) {
    if (n > biggestNumber) {
      biggestNumber = n
    }
  }
  return biggestNumber
}

console.log(getLargestNumber(NUMS))
// 127

Of course, as humans, we can look at that list and know the answer. But a computer needs a step by step process. So I have a variable biggestNumber where I hold the current largest number, and then I go over the list and keep replacing it if I find a bigger one. Then I return that.

This is similar to what you need to do with your strings, checking the length of the strings.

There are easier ways to solve the above, but I think working out a solution with a for loop is a good learning tool, to understand what is happening.

But again, to repeat, for your application, respuestaFinal should be a string, not an array.

Give that a try.

1 Like

Yes, they are the same. Why do I want to pass it in if it is available as a global?

  1. By using a global value, this function can only be used for that data. I would have to create a different function for every data set. That is really bad practice.
  2. Using global variables can create bugs. Your global variable might be changed or affected by something else.
  3. Writing a pure function (one that only depends on its parameters) is much, much, much easier to test. You may not be at a point of writing tests yet, but when you do, this will make a big difference.

In general, don’t use global variables. I mean, in my above example, I have the global variable NUMS, but I’m not using it as a global variable in the function - I am only using it in the global scope. In the scope of the function, it is a passed in reference, which makes the function pure - the function does not depend on anything outside the function (unless it is passed in as a parameter).

There are cases where you use global variables. For example, if a constant won’t change:

const PI = 3.14159265359;

That is not likely to change so keeping it as a global is fine. If I am writing a blog app and want to limit the number of comments per hour a user can make:

const MAX_COMMENTS_IN_HOUR = 25;

That might change, but it needs to be consistent across the app. And if it changes, I want to only change it in one spot, not 150. That makes sense to use a global constant there.

1 Like

All understood, Kevin!

Muchas gracias, este ejemplo me ha aclarado todo, y paso a paso, mentalmente, he comprendido como funciona en cada momento.
Es verdad!

const valores_global = [true, 5, false, "hola", "All understood, Kevin!", "adios", "no", 2];

function miFunction(valores) {
  const soloStrings = [];
  for (elemento of valores) {
    if (typeof elemento === "string") {
      soloStrings.push(elemento);
    }
  }
  let respuestaFinal = "";
  for (el of soloStrings){
    if(el.length > respuestaFinal.length){
      respuestaFinal = el;
    }
  }
  return respuestaFinal;
}
  
console.log(miFunction(valores_global));
//'All understood, Kevin!'

Si he entendido bien, creas la constante local entre [] para crear un array, utilizas loop for of para repasar todo el array entero, con un if para seleccionar solo las "strings", entonces utilizas push() para añadir esas strings a la variable local array.
Ahora, ya tengo las strings. Entonces utilizo un for of loop para recorrer todo el array de strings, y sustituye la variable local respuestaFinal por cada string que recorre. Si la siguiente string es más larga que la que hay ahora mismo en la variable respuestaFinal, sustituyela (con el if).
Ahora solo return el resultado (respuestaFinal) como valor resultante a la funcion miFunction() como parámetro la variable array global miFunction(valores_global)

No me se explicar muy bien, pero algo así seria no?

Si quieres, dime la otra forma más rápida de solucionarlo, y posteriormente me estudio lo que haga falta para aprenderla!
Igual, como es avanzado, más adelante. Se llamaba ¿reduccion?

Muchas gracias

Voy a tomar apuntes con ésta teoría! gracias