Ask Your Question
4

How can conditions be used to filter and map in JavaScript?

asked 2021-12-21 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-03-25 23:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-21 11:00:00 +0000

Seen: 12 times

Last updated: Mar 25 '22