js selects all even/odd/n multiples in a given array (filter)

js selects all even/odd/n multiples in a given array (filter)

1. Select all even numbers in the given array

use for

function collect_all_even(collection) {
    
    
  let res = [];
  for (let i of collection) {
    
    
    if (i % 2 === 0) {
    
    
      res.push(i);
    }
  }
  return res;
}

use filter

function collect_all_even(collection) {
    
    
  return collection.filter((x) => x % 2 === 0);
}

2. Select all odd numbers in the given array

Modify the condition in the above code to x % 2 === 1

3. Select the multiple of n in the given array

Modify the condition in the above code to x % n === 0

filter() method

The filter() method creates a new array containing all the elements that pass the tests fulfilled by the provided function.
grammar

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

callback
Function used to test each element of the array. Returning true means that the element passes the test and the element is retained, and false is not retained. It accepts the following three parameters :
1. The value of the element
element 2. index The index of the optional element
3. array Optional The array to be traversed itself
thisArg Optional The
value used for this when the callback is executed.
Return Value
A new array of elements that pass the test, or an empty array if no array elements pass the test.

filter does not change the original array, it returns the new filtered array

Guess you like

Origin blog.csdn.net/jojo1001/article/details/121355074