📜  map&filter - Javascript (1)

📅  最后修改于: 2023-12-03 15:32:48.842000             🧑  作者: Mango

Map & Filter - Javascript

Javascript provides two powerful array methods called map() and filter(). These methods can be used to transform and manipulate arrays in a variety of ways.

Map()

The map() function creates a new array by applying a function to each element in the original array. The function should take in one argument (the current element in the array) and return a new value. The new value will be added to the new array.

const numbers = [1, 2, 3, 4, 5];

const squaredNumbers = numbers.map((number) => {
  return number ** 2;
});

console.log(squaredNumbers);
// Output: [1, 4, 9, 16, 25]

In the example above, we use map() to create a new array called squaredNumbers. We pass in an arrow function that takes in the current number and returns the square of that number. The resulting array contains the squared values of the original array.

Filter()

The filter() function creates a new array by filtering out elements from the original array that do not meet a certain criteria. The function should take in one argument (the current element in the array) and return a boolean value. If the value is true, the element will be included in the new array. If the value is false, the element will be excluded.

const numbers = [1, 2, 3, 4, 5];

const oddNumbers = numbers.filter((number) => {
  return number % 2 !== 0;
});

console.log(oddNumbers);
// Output: [1, 3, 5]

In the example above, we use filter() to create a new array called oddNumbers. We pass in an arrow function that takes in the current number and returns a boolean value (true if the number is odd, false if the number is even). The resulting array contains only the odd numbers from the original array.

Conclusion

Map() and filter() are powerful tools that can simplify your code and make it more efficient. They are easy to use and can be applied to a wide variety of problems. By combining these functions with other array methods, you can create complex transformations and manipulations with just a few lines of code.