How to remove all even numbers from an array in JavaScript
Working with an array is unavoidable as a developer. Hence, it is important to know about all the array operations.
Here’s a guide on removing all the even numbers from an array in Javascript.
There’s no specific function in Javascript that removes all even numbers in an array. Still, various array operations can be performed to remove all the even numbers in an array.
This answer gives two methods to remove even numbers in an array with Javascript:
- The
forloop. - The
.filter()method.
The for loop
function removeEvenNumber(){let myArray = [3, 5, 6, 8, 10, 22, 25, 43, 46, 86];let newArray = [];for(let i = 0; i < myArray.length; i++){if(myArray[i] % 2 !== 0) newArray.push(myArray[i]);}console.log(newArray);}removeEvenNumber(); // [ 3, 5, 25, 43 ]
- Line 2: We declare an array.
- Line 4: We create an array. This array will hold the array after the even numbers have been removed.
- Line 6: We declare a for-loop. Then, we declare an
ifstatement, which assigns the odd numbers to thenewArray. The loop takes a value in the array and checks if it’s an even number, then assign it to thenewArrayif it’s not an even number.
The .filter() method
The example above uses the .filter() to remove the even numbers.
The .filter() method returns all the elements that pass a test passed into it as a callback function.
The callback function passed into the .filter() checks if an array value is an even number and returns the values that passed the test in a new array.
- Line 1: We create an array of numbers. It contains both odd and even numbers.
- In line 3: We declare a variable.Then, we assign to it the array created with the
.filter()method. - Line 4: This contains the content of the callback function of the
.filter()method. This function takes an array value and checks if, when divided by two, the remainder is not zero, such as an odd number. If the value passes the test, the function adds the value to a new array. Therefore, the new array will only contain the odd numbers( removing all the even numbers from the original array). - Line 5: The new array that contains the odd numbers is logged into the console.
Out of the both of the methods mentioned above, the .filter() method is the fastest to remove the even numbers of an array.
Free Resources