Filter array elements greater than a number in JavaScript
Beginner · 3 min read
Picking out the numbers above some limit is one of the most common things you will do with an array: prices over a budget, scores above a pass mark, temperatures above freezing. JavaScript's filter method does it in one line.
In this tutorial you will write largerThan(numbers, limit), and learn how filter works from scratch. Because the code is so short, the interesting parts are the edges: whether "larger than" includes equal, why the original array stays safe, and a trap when numbers arrive as text. You need to know what an array and an arrow function are.
What filter does
filter walks through an array and calls a function on every item. That function is called a predicate: it answers true ("keep this one") or false ("drop it"). filter collects the kept items into a new array, in their original order:
const ages = [12, 30, 17, 45];
console.log(ages.filter((age) => age >= 18)); // [ 30, 45 ]
The arrow function (age) => age >= 18 is the predicate. For 12 it gives false, for 30 true, and so on.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
19 Elements larger than a number
easyReturn the array elements greater than a given number.
Stuck? Three hints, smallest first
- 1.
filteris the whole answer. - 2. Decide whether "larger than" includes equal. Name the function so it says.
- 3.
filterreturns a new array; the original is untouched.
Step 1: keep the numbers above the limit
Wrap filter in a function that takes the array and the limit:
const largerThan = (numbers, limit) => numbers.filter((n) => n > limit);
const values = [1, 5, 12, 3, 20, 5, -4];
console.log(largerThan(values, 5)); // [ 12, 20 ]
The predicate (n) => n > limit uses limit from the outer function. An inner function can always read the variables of the function it sits inside.
Step 2: does "larger than" include equal?
In everyday English, "numbers larger than 5" is a little vague about 5 itself. Code can't be vague. > leaves the fives out. >= keeps them:
const atLeast = (numbers, limit) => numbers.filter((n) => n >= limit);
console.log(atLeast(values, 5)); // [ 5, 12, 20, 5 ]
The answer writes two functions with names that say which they do, largerThan and atLeast. That is clearer than one function with a true-or-false switch, because anyone reading atLeast(prices, 100) knows what it means without looking it up.
Step 3: the original stays the same
filter never changes the array you call it on. It builds a separate one:
const bigger = largerThan(values, -100);
console.log(values); // [ 1, 5, 12, 3, 20, 5, -4 ]
console.log(bigger === values); // false
Even when every item passes, you get a new array, not the same one. That is what makes it safe to chain calls like largerThan(values, 0).filter(...) without worrying about the data you started with.
Step 4: pass the test in as a parameter
largerThan is just one kind of test. If the function takes the predicate itself as a parameter, the caller can ask any question:
const where = (numbers, passes) => numbers.filter(passes);
console.log(where(values, (n) => n < 0)); // [ -4 ]
console.log(where(values, (n) => n % 2 === 0)); // [ 12, 20, -4 ]
n % 2 === 0 is true for even numbers. This is exactly how filter itself is designed: you hand it the test.
Step 5: numbers that are really text
Data from forms, files or web requests often arrives as text, like '10' instead of 10. Comparing text with a number using > quietly converts the text to a number first:
console.log('10' > 5); // true
console.log(largerThan(['10', 9], 5)); // [ '10', 9 ]
That looks fine. The trouble is that the '10' you kept is still text, and later code may treat it as text. Comparing two strings, for example, goes letter by letter, so '9' > '10' is true. Convert at the start with map(Number), so everything after that is a real number:
console.log('9' > '10'); // true
console.log(largerThan(['10', 9].map(Number), 5)); // [ 10, 9 ]
The full solution
The panel has largerThan, atLeast and where. It prints the numbers above 5, the numbers of at least 5, the untouched input, two custom tests and the text-number case. Press Run to see them.
const largerThan = (numbers, limit) => numbers.filter((n) => n > limit);
const atLeast = (numbers, limit) => numbers.filter((n) => n >= limit);
// Taking the test as a parameter, which is what filter itself does.
const where = (numbers, passes) => numbers.filter(passes);
const values = [1, 5, 12, 3, 20, 5, -4];
console.log('larger than 5 :', largerThan(values, 5));
console.log('at least 5 :', atLeast(values, 5), '<- includes the fives');
console.log('input :', values, '<- unchanged');
console.log('below zero :', where(values, (n) => n < 0));
console.log('even :', where(values, (n) => n % 2 === 0));
console.log('--- filter never coerces, so a string does not compare numerically ---');
console.log("['10', 9] larger than 5:", largerThan(['10', 9], 5), '<- string "10" > 5 is true by coercion');
Output
18 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 18 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('elements above 5', largerThan(values, 5), [12, 20]);
test('at least 5 includes the fives', atLeast(values, 5), [5, 12, 20, 5]);
test('and so has more entries', atLeast(values, 5).length > largerThan(values, 5).length, true);
test('the original array is untouched', values, [1, 5, 12, 3, 20, 5, -4]);
test('a limit above everything gives nothing', largerThan(values, 100), []);
test('a limit below everything gives all of it', largerThan(values, -100).length, values.length);
test('an empty array gives an empty array', largerThan([], 5), []);
test('negatives compare correctly', largerThan(values, -5), [1, 5, 12, 3, 20, 5, -4]);
test('because -4 is greater than -5', -4 > -5, true);
test('while a limit of -4 excludes it', largerThan(values, -4), [1, 5, 12, 3, 20, 5]);
test('a new array is returned, not the same one', largerThan(values, -100) === values, false);
test('duplicates are all kept', largerThan([6, 6, 6], 5), [6, 6, 6]);
test('the predicate version can do anything', where(values, (n) => n < 0), [-4]);
test('including a completely different test', where(values, (n) => n % 2 === 0), [12, 20, -4]);
test('filter keeps order', largerThan([20, 1, 12], 5), [20, 12]);
test('numeric strings are coerced by >', largerThan(['10', 9], 5), ['10', 9]);
test('so filtering mixed types compares loosely', '10' > 5, true);
test('which is worth converting first to avoid', largerThan(['10', 9].map(Number), 5), [10, 9]);
One line of filter, so the value is in the edges. Naming matters: "larger than" is ambiguous about equality in English and not at all ambiguous in code, so largerThan and atLeast are separate functions rather than a boolean flag. The assertion that one returns more entries than the other keeps them honest.
filter always returns a new array, so the input is safe — asserted, because it is the property that lets you chain these calls without thinking.
The last few assertions are the trap: '10' > 5 is true, because > coerces the string to a number. So filtering an array of mixed strings and numbers appears to work and then compares '9' and '10' as text in some other operation. Convert at the boundary with .map(Number).
Common mistakes
- Using
>when you meant>=. The limit itself is left out. Decide which you need and name the function to match. - Forgetting to
returnin a curly-brace predicate.filter((n) => { n > 5 })returns nothing, so every item is dropped. Either drop the braces or writereturn n > 5. - Filtering numbers stored as text. Comparisons mostly work, but the results are still strings. Convert with
map(Number)first.
Try it yourself
- Write
between(numbers, low, high)that keeps numbers fromlowtohigh, including both ends. - Use
whereto keep only the numbers that are multiples of 5 in[1, 5, 12, 3, 20, 5, -4]. - Write
countLargerThan(numbers, limit)that returns how many numbers are above the limit. Try it once withfilter(...).lengthand once withreduce.