How to traverse an element by one in a JS array

Asked

Viewed 1,379 times

-2

Come on, guys, good afternoon. I’m doing a function that has the same utility as ANY.

What is the idea, is to know if it has any number smaller than the given in the function inside the array, regardless of whether it is at the first or last position of the array. If exister returns TRUE, if not, return FALSE

The code is like this:

const numerosFora = [1];

function qualquer (num1, func){
	for(let i = 0; i < num1.length; i++){
  	for(let i = 0; i < func.length; i++){
    	if(num1[i] < func[i]){
      		return true
      } else {
       		return false
      }
      	
      }
    }
  	
}

  

console.log(qualquer([1,0],numerosFora))

However it returns only if the number is in the first position, in case 0.

  • 2

    The question is not clear and I did not understand the code properly either. Why does not use any?

  • @Lucascosta Fala Lucas, good afternoon. The idea is for me to create my own Any, got it? any, got it? I want to know how I move from one element to the other in the array. EXAMPLE: Knowing if there is a number 3 in the array: Array = [1,2,3,4] I want to know how to go through 3 and return true, got it? And if it returns false, it goes next, until the last, got it? In mine, it goes to only the first and returns.

  • 1

    Starts the error that you have 2 nested loops using the same variable "i", should be two different variables, no?

3 answers

1

If you need to test an array to see if any of its elements satisfy a condition use the method Array.prototype.some().

The method some() accepts a callback function and evokes it once for each element of the array until such time as this callback function returns true.

/**
 * Procura em um array por um valor menor que o valor indicado. 
 * @param {Array} arr - O array cujo os elementos serão testados contra val.
 * @param {number} val - O valor a ser testado contra os elementos de arr. 
 * @returns {boolean} retorna true quando encontrar em arr um elemento menor que val caso o contrário retorna false.
 */
function menorQue(arr, val) {
  return arr.some((e) => {
    return e < val;
  });
}

let lista = [2, 3, 4, 5, 6];

console.log(menorQue(lista, 10));

console.log(menorQue(lista, 2));

Another interpretation for your question due to this statement const numerosFora = [1];, would be to compare two arrays and return true if an element smaller than the second is found in the first array.

/**
 * Procura em arr1 por um elemento que seja menor que um dos valores de arr2. 
 * @param {Array} arr1 - Array cujo os elementos serão testados.
 * @param {Array} arr2 - Array cujo os elementos serão testados.
 * @returns {boolean} retorna true quando encontrar em arr1 um elemento menor que qualque um dos elementos de arr2.
 */
function algumMenorQue(arr1, arr2) {
  return arr1.some((e) => {
    return arr2.some((e1) => {
      return e < e1;
    })
  });
}

let lista = [2, 3, 4, 5, 6];


console.log(algumMenorQue(lista, [7, 8, 9]));

console.log(algumMenorQue(lista, [0, 1]));

0

Their for have problem because both use the same variable i, therefore, in comparison num1[i] < func[i], the i will always be the last for.

Another thing, when you put one return, the loop ends, that is, the remaining items of the array that should perhaps be traversed, will no longer be.

How do you just check if it returns true and stop the loop when it happens, just let the return true in the loop (and change the second variable for):

const numerosFora = [1];

function qualquer (num1, func){
  for(let i = 0; i < num1.length; i++){
    for(let x = 0; x < func.length; x++){
      if(num1[i] < func[x]){
        return true;
      }else{
        console.log(false); // apenas como exemplo para mostrar no console
      }
    }
  }
}

console.log(qualquer([1,0],numerosFora))

0

Javascript ES6 it would be something like that:

const qualquer = (a, b) => {
  return a.map(item1 => b.map(item2 => item1 < item2 ? true : false));
}

console.log(qualquer([1, 2, 3, 4], [1, 3, 5])); 

   //Resultado
   //0: (3) [false, true, true]
   //1: (3) [false, true, true]
   //2: (3) [false, false, true]
   //3: (3) [false, false, true]

Browser other questions tagged

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