How to use filter() Method In Javascript
It is used to filter the array and apply the callback function to each item of the array and filter the element which returns true against the callback function.
Syntax:
Array.filter( callback )
Example: In this example, we will be using the Javascript filter() method to remove the elements from the end of a given array.
// Define the array
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log("Original Array:", arr);
// Define the number of elements to remove
let elemsToDelete = 5;
// Loop for the number of elements
// to delete
let k = arr.filter((x, i) =>
i + elemsToDelete < arr.length)
// Pop the last element from the
// end of the array
console.log("Modified Array:", k);
Output
Original Array: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] Modified Array: [ 1, 2, 3, 4 ]
How to remove n elements from the end of a given array in JavaScript ?
In this article, we will learn how to remove the last n elements from the end of the given array in JavaScript.
We can remove n elements from the end of a given array in the following ways:
Table of Content
- Method 1: Using splice() Method
- Method 2: Using pop() Method
- Method 3: Using filter() Method
- Method 4: Using Array slice() method
- Method 5: Using while loop
Contact Us