Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map and Filter mapped array in Javascript

Tags:

javascript

This a very simple question. I want to map and form an array given another array. then I would like to remove the duplicated values.

this is what I did:

let status = listHotels.map(hotel => {
  return hotel.status
})

const x = status.filter((v, i) => (
  status.indexOf(v) === i
));

It works. But I would like a solution that doesn't involve writing two blocks of code. I tried this:

let status = listHotels.map(hotel => {
  return hotel.status
}).filter((v, i) => (
  status.indexOf(v) === i
));

But it didnt work. It says

Cannot read property 'indexOf' of undefined

Does anyone know a workaround this?

like image 991
Jeff Goes Avatar asked Dec 18 '22 19:12

Jeff Goes


1 Answers

status is still not defined when you call the .filter method.

change your code to:

const listHotels = [{status:'s1'}, {status:'s1'}, {status:'s2'}]
let status = listHotels.map(hotel => {
  return hotel.status
}).filter((v, i, currentStatus) => (
  currentStatus.indexOf(v) === i
));
console.log(status);
like image 180
Karim Avatar answered Dec 20 '22 07:12

Karim