Middle
What array processing methods do you know?
sobes.tech AI
Answer from AI
In JavaScript, there are many methods for working with arrays that allow for efficient data processing and transformation. Here are the main ones:
- forEach — iterates over each element of the array, executing a function, but does not return a new array.
- map — creates a new array by applying a function to each element of the original array.
- filter — creates a new array containing elements that satisfy a condition.
- reduce — reduces the array to a single value by applying an accumulator function.
- find — returns the first element that satisfies a condition.
- some — checks if at least one element satisfies a condition.
- every — checks if all elements satisfy a condition.
- sort — sorts the array based on a given criterion.
- concat — combines arrays.
- slice — returns a part of the array without modifying the original.
Example of using map and filter:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const even = numbers.filter(n => n % 2 === 0); // [2, 4]
These methods allow writing clean and readable code when working with arrays.