Easy

Integers Greater Than

Prompt

Create a function named integersGreaterThan that takes two arguments:

  • n: A number representing the threshold.
  • arr: An array of integers.

The function should return a new array containing only the integers from arr that are strictly greater than n.

Playground

Hint 1

JavaScript arrays have a built-in filter method that creates a new array with only the elements that pass a test you define.

Hint 2

The callback you pass to filter receives each element. You just need to return true when the element is greater than n and false otherwise. An arrow function like (num) => num > n does exactly that.

Solution

Explanation

This is a warm-up problem, but it's a good one because it checks whether you know about Array.prototype.filter, which is one of the most commonly used array methods in JavaScript.

The filter method iterates over every element in the array and builds a new array containing only the elements for which the callback returns a truthy value. It doesn't modify the original array, which is exactly what the problem asks for: "return a new array."

The callback (num) => num > n is about as simple as it gets. For each number, it checks whether that number is strictly greater than n. If it is, the number makes it into the result. If it's equal to or less than n, it gets excluded.

One subtle thing to be aware of: the comparison is strict (>), not greater-than-or-equal (>=). That means if n is 10 and the array contains 10, that 10 does not appear in the output. This matches the problem description, which says "greater than," not "greater than or equal to."

You could also solve this with a for loop and an empty array that you push qualifying elements into. That approach works, but filter communicates the intent more clearly and is what most interviewers expect when the problem is this straightforward.