You can find all odd numbers in a JavaScript array by:
You should avoid checks for odd numbers with "n % 2 === 1" (where n is an integer, and % is the remainder operator) because, for negative numbers, this would return -1. Therefore, it may be easier to simply check if the number is not an even number (i.e. n % 2 !== 0) because it accounts for both, negative and positive numbers (since -0 === 0 in JavaScript). Otherwise, you would need an extra/explicit check for negative numbers.
#Using Array.prototype.filter()
To get all odd 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 oddNumbers = numbers.filter(function (number) {
return number % 2 !== 0;
});
console.log(oddNumbers); // [-5, -1, 1, 3, 7]
This would return a new array containing all odd 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 oddNumbers = numbers.filter((number) => number % 2 !== 0);
console.log(oddNumbers); // [-5, -1, 1, 3, 7]
When no matches are found, an empty array is returned:
// ES6+
const numbers = [-2, 0, 4];
const oddNumbers = numbers.filter((number) => number % 2 !== 0);
console.log(oddNumbers); // []
#Using a Loop
You can loop over an array of integers and create a new array to which you add all odd numbers to, for example, like so:
const numbers = [-5, -2, -1, 0, 1, 3, 4, 7];
const oddNumbers = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 !== 0) {
oddNumbers.push(numbers[i]);
}
}
console.log(oddNumbers); // [-5, -1, 1, 3, 7]
This would return a new array containing all odd numbers, and when no match is found, an empty array is returned.