You can find all even numbers in a JavaScript array by:
The check for even numbers can be done using the remainder operator (%
), where an even number would return true
if n % 2 === 0
(where n
is an integer).
Using Array.prototype.filter()
To get all even numbers in an array of integers using the Array.prototype.filter()
method, you can do the following:
// ES5+ const numbers = [-5, -2, -1, 0, 1, 3, 4, 7]; const evenNumbers = numbers.filter(function (number) { return number % 2 === 0; }); console.log(evenNumbers); // [-2, 0, 4]
This would return a new array containing all even numbers. In ES6+, you can shorten this to a one-liner using the arrow function syntax:
// ES6+ const numbers = [-5, -2, -1, 0, 1, 3, 4, 7]; const evenNumbers = numbers.filter((number) => number % 2 === 0); console.log(evenNumbers); // [-2, 0, 4]
When no matches are found, an empty array is returned:
// ES6+ const numbers = [-5, -1, 1, 3, 7]; const evenNumbers = numbers.filter((number) => number % 2 === 0); console.log(evenNumbers); // []
Using a Loop
You can loop over an array of integers and create a new array to which you add all even numbers to, for example, like so:
const numbers = [-5, -2, -1, 0, 1, 3, 4, 7]; const evenNumbers = []; for (let i = 0; i < numbers.length; i++) { if (numbers[i] % 2 === 0) { evenNumbers.push(numbers[i]); } } console.log(evenNumbers); // [-2, 0, 4]
This would return a new array containing all even numbers, and when no match is found, an empty array is returned.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.