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

350
Vistas
Is there any way to filter a string in an array of integers in JavaScript?

I have a JavaScript array :

const arr = ['a', 'b', 1, 4, 6, 'John', 9, 91];

I want to only keep the integers and filter out the strings and characters. Is there any way to do it ? I tried with typeof() but it is not working. Thanks in advance.

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

0

You can use Array.prototype.filter and filter out the items which are numbers using the typeof operator.

const 
  arr = ["a", "b", "1", 4, 6, "John", 9, 91],
  nums = arr.filter((a) => typeof a === "number");

console.log(nums);

Another approach

You can also do it coercing the items to a number. The strings which cannot be coerced to a number result in NaN, a falsy value in JS, and hence are filtered out.

const 
  arr = ["a", "b", 1, 4, 6, "John", 9, 91],
  nums = arr.filter(Number);

console.log(nums);

But note strings that can be coerced to numbers like "1", "123" etc will not get filtered out by the second approach.

And more importantly this approach would filter out all zeroes (0, "0") in the array as 0 is a falsy value in JS.

const 
  arr = ["1", "4", "6", 0, "0"],
  nums = arr.filter(Number);

console.log(nums);

Filtering Integers

You can also filter only integers using Number.isInteger

const 
  arr = ["1", 2, -3, 4.5],
  ints = arr.filter(Number.isInteger);

console.log(ints);

But note, this approach would not filter out numbers where the integral part of the number is equal to the number itself. In other words simply appending zeroes after the decimal point (like 1.00000) would not yield false when passed to isInteger.

const 
  arr = [1.0, 2.01],
  ints = arr.filter(Number.isInteger);

console.log(ints);

about 4 years ago · Juan Pablo Isaza Denunciar

0

try this:

arr.filter((elem) => Number.isInteger(elem));

output = [1,4,6,9,91]
about 4 years ago · Juan Pablo Isaza Denunciar

0

   const arr = ['a', 'b', 1, 4, 6, 'John', 9, 91];

const number = arr.filter(item => typeof item === 'number')
console.log(number )

here the correct way

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