-1

I am trying to check if the arguments passed to duckCount have the property 'quack' and return the number of arguments that do have it.

To do so I was trying to use the filter on the arguments array but for some reason I can't. Anyone knows why?

var notDuck = Object.create({ quack: true })
var duck = { quack: true }

duckCount(duck, notDuck) // 1

function duckCount() {
  // SOLUTION GOES HERE
  console.log(arguments)
  return arguments.filter((argument) => argument.hasOwnProperty('quack')).length
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
MigthyMoron
  • 119
  • 9

2 Answers2

1

arguments is an object but not an array where as filter is an array function. Use the rest parameter to convert the argument object to array and then apply array function

var notDuck = Object.create({
  quack: true
})
var duck = {
  quack: true
}
// 1

function duckCount() {
  // SOLUTION GOES HERE
  console.log(arguments)
  return [...arguments].filter((argument) => argument.hasOwnProperty('quack')).length
}

console.log(duckCount(duck, notDuck))

You can also use Array.from to a new instance from array like object

var notDuck = Object.create({
  quack: true
})
var duck = {
  quack: true
}
// 1

function duckCount() {
  return Array.from(arguments).filter((argument) => argument.hasOwnProperty('quack')).length
}

console.log(duckCount(duck, notDuck))
brk
  • 48,835
  • 10
  • 56
  • 78
0

brk's solution is the best way if you can guarantee that your code will only ever run on browsers which support ES6 (which these days mainly means "not IE") - but sometimes you do have to support older browsers. (This probably doesn't apply to the OP, due to the use of arrow functions, but this might be useful for others.) In case you need to, there is a useful trick which is barely any more bother than using array destructuring or Array.from:

return Array.prototype.filter.apply(arguments, function(argument) {/* your function goes here */});
Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34