'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.



Solution 1:[1]

const result = arr.reduce((acc,curr) => {
 return curr.token !==undefined ? [...acc,curr.token] : acc
},[])

Solution 2:[2]

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()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GrimReaper07
Solution 2 Tushar Shahi