0

i want to have reusable function that maps an array of objects based on property passed as parameter to function.

Here's my code:

let arr = [
  {
    country: 'poland',
    population: 380000
  },
  {
    country: 'bangladesh',
    population: 3492423
  }
]

function filterMyArr (myArr, condition) {
  return myArr.map(element => element.country)
}

console.log(filterMyArr(arr))

When i change code and try to pass condition, while executing it doesn't work. I want to call a function with second parameter for example filterMyArr(arr, country) and to have similar outcome. I want it to be reusable so i can use it for population or any other property. Thank you.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Kamil Staszewski
  • 303
  • 7
  • 20

3 Answers3

6

You just need to use bracket notation, like this:

function filterMyArr (myArr, condition) {
  return myArr.map(element => element[condition])
}

Where you pass the condition as a string as a name of a property in your object.

Note:

But just be aware that calling the function without this condition argument, will throw an error, when you do:

console.log(filterMyArr(arr))
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
2

You were very close. Try this

let arr = [
  {
    country: 'poland',
    population: 380000
  },
  {
    country: 'bangladesh',
    population: 3492423
  }
]

function filterMyArr (myArr, condition) {
  return myArr.map(element => element[condition])
}

console.log('Countries - ', filterMyArr(arr, 'country'))

console.log('Population - ', filterMyArr(arr, 'population'))
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
0

You need to pass second argument (property) as a string and access it using bracket notation:

let arr = [
  {country: 'poland', population: 380000},
  {country: 'bangladesh', population: 3492423}
];

function filterMyArr (myArr, prop) {
  return myArr.map(obj => obj[prop]);
}

console.log(filterMyArr(arr, 'country'));
console.log(filterMyArr(arr, 'population'));
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95