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

97
Vistas
Why function output doesn't return an expected array

This should be something simple, but I miss why this code outputs 'undefined', while I expect to get an array with numbers: [1, 2]. I tried to debug it in console step by step, but still don't understand why newArr doesn't return from the function. Could someone explain, please.

function filterList(arr) {
    let newArr = []
    for(let i = 0; i <= arr.length; i++) {
        if (typeof arr[i] !== "number") {
            return
        }
        if (typeof arr[i] === 'number') {
            newArr.push(arr[i])
        }
    }
    return newArr
}

console.log(filterList([1,2,'a','b']))

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The first return that is reached inside a function will end the function call and will return whatever you set there.

In your case, you are pushing 2 values in the array, but as soon as you reach the third one a you are just using return. This means that you are returning undefined. You should return newArr

function filterList(arr) {
    let newArr = []
    for(let i = 0; i <= arr.length; i++) {
        if (typeof arr[i] !== "number") {
            return newArr
        }
        if (typeof arr[i] === 'number') {
            newArr.push(arr[i])
        }
    }
    return newArr
}

console.log(filterList([1,2,'a','b']))
about 4 years ago · Juan Pablo Isaza Denunciar

0

remove return in for loop

function filterList(arr) {
    let newArr = []
    for(let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === 'number') {
            newArr.push(arr[i])
        }
    }
    return newArr
}
const arr = [1,2,'a','b']
console.log(filterList(arr))

// with Array.filter
let result1 = arr.filter(ele => typeof ele === 'number')
console.log(result1)

// with Array.reduce
let result2 = arr.reduce((res, ele) => typeof ele === 'number' ? [...res, ele] : res, [])
console.log(result2)

function stopFunc(isStop = false) {
  let total = 0
  for(let i = 0; i < 10; i++) {
    total += i
    if(isStop) return 999
  }
  return total // return 45
}
console.log(stopFunc())
console.log(stopFunc(true))

you can check stopFunc function in my example, The return statement ends function execution and specifies a value to be returned to the function caller. . in your function :

if (typeof arr[i] !== "number") {
   return
}

return omitted, undefined is returned instead.

You can check document return

about 4 years ago · Juan Pablo Isaza Denunciar

0

You're returning from the function immediately on finding an element that isn't a number, and the return value from the function is undefined not the array you've been patiently pushing numbers into. Just remove that statement altogether.

function filterList(arr) {

  const newArr = [];

  for (let i = 0; i <= arr.length; i++) {
    if (typeof arr[i] === 'number') {
      newArr.push(arr[i]);
    }
  }

  return newArr;

}

console.log(filterList([1, 2, 'a', 'b', 3, 4]))

about 4 years ago · Juan Pablo Isaza Denunciar
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