Remove all even numbers from an array of numbers?

Answered
suparman21 asked this question 4 months ago
suparman21 on Jan 19 · Edited

I have a JavaScript array that contains several numbers:

[1, 5, 3, 22, 21, 43, 43, 432, 346]

How do I remove each element in that array that is an even number?

It should look like this after removing each even number (only odd numbers remain):

[1, 5, 3, 21, 43, 43]
4 suggested answers
coderguy on Jan 20 · Edited
array.filter(function(number) {
  return number % 2 !== 0
})

This code uses the filter() array method to remove all even numbers.

0 replies
yaboy01 on Jan 20

Here's a method using a simple for() loop:

let array = [1, 5, 3, 22, 21, 43, 43, 432, 346]

var newArray = []

for (var i=0; i < array.length; i++) {
  if (array[i] % 2 !== 0) newArray.push(array[i])
}

// newArray = [ 1, 5, 3, 21, 43, 43 ]

You can convert this method into a function like this:

function removeEvens(array) {
  var newArray = []

  for (var i=0; i < array.length; i++) {
    if (array[i] % 2 !== 0) newArray.push(array[i])
  }

  return newArray
}

This function takes an array as a parameter, removes the even numbers from it, and returns the new array that contains only odd numbers.

0 replies
moon_man41 on Jan 20

ES6 version of the filter() method:

array.filter(value => value % 2 !== 0)
0 replies
nick on Jan 20

Lodash has a remove() method you can use:

_.remove(array, function(num) {
  return num % 2 !== 0
})

That removes each even element from the array of numbers.

0 replies
Answered