js how to filter range imutable array
- Published
- Reading time
- 2 min read
- Length
- 329 words
On this page
How to Filter a Range Immutable Array in JavaScript#
Filtering an immutable array in JavaScript can be challenging, especially when it comes to filtering a range of elements. However, there are several ways to filter a range immutable array in JavaScript.
Method 1: Using the filter() Method#
The filter() method creates a new array with all elements that pass the test implemented by the provided function. Here is how you can use it to filter a range immutable array:
const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.filter((item, index) => index >= 2 && index <= 4);
console.log(filteredArr); // Output: [3, 4, 5]In this example, the filter() method checks each element of the array and returns a new array that contains only the elements with an index value between 2 and 4 (inclusive).
Method 2: Using the slice() Method#
The slice() method extracts a section of an array and returns a new array. Here is how you can use it to filter a range immutable array:
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.slice(2, 5);
console.log(slicedArr); // Output: [3, 4, 5]In this example, the slice() method extracts a section of the array with index values between 2 and 4 (exclusive) and returns a new array.
Method 3: Using the spread operator#
The spread operator (...) can be used to copy and merge arrays. Here is how you can use it to filter a range immutable array:
const arr = [1, 2, 3, 4, 5];
const filteredArr = [...arr.slice(2, 5)];
console.log(filteredArr); // Output: [3, 4, 5]In this example, the slice() method extracts a section of the array with index values between 2 and 4 (exclusive), and the spread operator merges it into a new array.
Conclusion#
Filtering a range immutable array in JavaScript can be accomplished using the filter() method, slice() method, or spread operator. Each method has its own advantages and disadvantages, so choose the one that suits your needs best.