Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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 answers
Answer question

0

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

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!