daggett
daggett

Reputation: 277

.filter not a function error?

Created a function that returns the sum of the two lowest positive integers from an array. My problem is that it seems to work fine on CodeWars website, but when I run it in Chrome console it's giving me the .filter is not a function error. I suspect its a syntax error in the arrow functions, but I can't for the life of me work it out!

function sumTwoSmallestNumbers(numbers) {
  const filter = numbers.filter(x => x > -1).sort((a, b) => a - b);
  return filter[0] + filter[1];
}

sumTwoSmallestNumbers(544, 32654, 34297, 9237, 343, 98); // 441

Upvotes: 0

Views: 13888

Answers (4)

Mamun
Mamun

Reputation: 68923

In JavaScript, filter is a method implemented on array. You have to pass the parameter (numbers) in the form of an array:

function sumTwoSmallestNumbers(numbers) {
  const filter = numbers.filter(x => x > -1).sort((a, b) => a - b);
  return filter[0] + filter[1];
}

console.log(sumTwoSmallestNumbers([544, 32654, 34297, 9237, 343, 98])); 

Upvotes: 1

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28465

Use Rest parameters to represent an indefinite number of arguments as an array.

function sumTwoSmallestNumbers(...numbers) {
  const filter = numbers.filter(x => x > -1).sort((a, b) => a - b);
  return filter[0] + filter[1];
}

console.log(sumTwoSmallestNumbers(544, 32654, 34297, 9237, 343, 98));

Upvotes: 1

Giannis Mp
Giannis Mp

Reputation: 1309

You have to use an array like so:

function sumTwoSmallestNumbers(numbers) {
  const filter = numbers.filter(x => x > -1).sort((a, b) => a - b);
  return filter[0] + filter[1];
}

console.log(sumTwoSmallestNumbers([544, 32654, 34297, 9237, 343, 98])); // 441

Upvotes: 2

vibhor1997a
vibhor1997a

Reputation: 2376

You need to pass an array like,

function sumTwoSmallestNumbers(numbers) {
  const filter = numbers.filter(x => x > -1)
  filter.sort((a, b) => a - b);
  return filter[0] + filter[1];
}

console.log(sumTwoSmallestNumbers([544, 32654, 34297, 9237, 343, 98])); // 441

Or in ES6 you can use spread operator like,

    function sumTwoSmallestNumbers(...numbers) {
      const filter = numbers.filter(x => x > -1)
      filter.sort((a, b) => a - b);
      return filter[0] + filter[1];
    }

    console.log(sumTwoSmallestNumbers(544, 32654, 34297, 9237, 343, 98)); // 441

Upvotes: 2

Related Questions