Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
How to Use If in Loop to Return Message for No Results

Purpose: This allows you to choose a target number and then will identify two numbers from the array that sum to be the target number.

Question: How do I add a message when there are no two numbers in the array that sum to be the target number?

What I've tried: Tried doing else with a console.log message when result === 0, also tried when result === [], and result === [0]. Tried doing another if statement. I think I am getting the syntax and/or placement wrong.

Code:

const twoSum = (array, target) => {
    let result = [];
    for (i = 0; i < array.length; i++) {
        if(array[i] > target) {
            continue;
        }
        if(array.includes(target - array[i])) {
            result.push(array[i]);
            result.push(target - array[i]);
            break;
        }
        if(result.length < 1){
            console.log("The array does not have two numbers that sum to equal your target value.")
            break;
        }
    }
    return result;
};
let array = Array.from({length: 10000}, () => Math.floor(Math.random() * 10000));
const target = 2;
console.log(twoSum(array, target));
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda