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

113
Vistas
JS - Filter array of objects returning only a specific field (some kind of combination between map and filter)

I have the following array

const arr = [
  { id: 1, token: "aAdsDDwEwe43svdwe2Xua" }, 
  { id: 2, token: undefined }
];

And I need to filter out undefined tokens, and ignore the id field.

Something like:

const arr = [
  { id: 1, token: "aAdsDDwEwe43svdwe2Xua" },
  { id: 2, token: undefined },
];

const result = arr
  .filter(({ token }) => token !== undefined)
  .map(({ token }) => token);
  
console.log(result);

Is it possible to do it in O(n) ? I mean, without navigating through the list twice.

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

0

const result = arr.reduce((acc,curr) => {
 return curr.token !==undefined ? [...acc,curr.token] : acc
},[])
about 4 years ago · Juan Pablo Isaza Denunciar

0

Firstly it is O(n). Just because we run over a loop two times, it does not become O(n^2).

Additionally, if you simply use a for loop you will realise how simple it is:

const arr = [
  { id: 1, token: "aAdsDDwEwe43svdwe2Xua", extraField : "x" }, 
  { id: 2, token: undefined, extraField : "x" }
];

let ans = [];

for(let i = 0 ; i < arr.length; i++){
if(arr[i].token!== undefined){
let { id, ...newBody } = arr[i];
ans.push(newBody);
}
}

console.log(ans);

Used spread operator (...), to remove a particular property (here id). If you are looking for array methods, the above could also be achieved using a .forEach()

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