Home > Software engineering >  Filter an array with boolean array in javascript
Filter an array with boolean array in javascript

Time:11-17

I have two lists:

let cities = ["Istanbul", "Ankara", "Izmir"];
let filterVals = [true, false, false];

I need to filter cities using filterVals array.

In the example, I'm expecting only "Istanbul" for example.

CodePudding user response:

It's as easy as a simple one-liner:

cities.filter((city, index) => filterVals[index])

const cities = ["Istanbul", "Ankara", "Izmir"];
const filterVals = [true, false, false];

const result = cities.filter((city, index) => filterVals[index]);

console.log(result);

CodePudding user response:

you can do this

let cities = ["Istanbul", "Ankara", "Izmir"];
let filterVals = [true, false, false];


const newCities = cities.filter((city, index) => filterVals[index]);

console.log(newCities);

  • Related