1 | initial version |
In JavaScript, conditions can be used to filter and map arrays.
Filter:
The filter() method creates a new array with all elements that pass the test implemented by the provided function. The provided function takes in the current element being processed and returns a boolean value indicating whether the element should be included in the new array.
Here's an example:
const numbers = [1, 2, 3, 4, 5];
const filteredNumbers = numbers.filter(function(number) {
return number > 2;
});
console.log(filteredNumbers); // Output: [3, 4, 5]
In this example, the filter() method is used to create a new array called filteredNumbers that contains only the elements of the original numbers array that are greater than 2.
Map:
The map() method creates a new array with the results of calling a provided function on every element in the calling array. The provided function takes in the current element being processed and returns a new value for that element.
Here's an example:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
In this example, the map() method is used to create a new array called doubledNumbers where each element of the original numbers array is multiplied by 2.