Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map with a conditional in Javascript

I'm traversing through an object array:

people = [
  {id:1, name:"Bob", available:false},
  {id:2, name:"Sally", available:true},
  {id:1, name:"Trish", available:false},
]

I want my output to be the names of those available:

["Sally"]

I currently know how to map and extract for a field. How do I add the conditional?

  const peopleAvailable = people.map(person => person.value);

Want to do something like this:

  const peopleAvailable = people.map(person.available => person.value);
like image 780
lost9123193 Avatar asked Jul 18 '26 22:07

lost9123193


1 Answers

You cannot conditionally map with the .map() function alone, however you can use .filter() to achieve what you require.

Calling filter will return a new array where each item in the new array satisfies your filtering criteria (ie people.available === true).

In the case of your code, you can directly chain filter with your existing call to .map() to obtain the desired result:

const people = [{
    id: 1,
    name: "Bob",
    available: false
  },
  {
    id: 2,
    name: "Sally",
    available: true
  },
  {
    id: 1,
    name: "Trish",
    available: false
  },
];

const peopleAvailable = people
.filter(people => people.available)    /* filter available people */
.map(person => person.name)            /* map each person to name */ 

console.log(peopleAvailable);
like image 100
Dacre Denny Avatar answered Jul 21 '26 10:07

Dacre Denny