Open In App

JavaScript equivalent of Python slicing

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, slicing is a very easy method to get the parts of a list, string, or other iterable. When we move to JavaScript, we don't have an exact equivalent of Python's slicing. In this article, we will explore javascript methods that are equivalent to Python slicing.

Let’s explore how we can slice arrays and strings in JavaScript.

Using the slice() Method

In JavaScript, the most straightforward way to slice an array or string is by using the slice() method. This method works very similarly to Python's slicing.

JavaScript
let str = "Hello, World!";

// Slicing from index 7 to the end
let newStr = str.slice(7);

console.log(newStr); 

Output
World!

Other methods that we can use in place of python's slicing are:

Using substring() Method

Another way to slice strings or arrays is using the substring() method. It’s a bit less flexible than slice() but still useful.

JavaScript
let str = "Hello, World!";
let newStr = str.substring(7, 12);

console.log(newStr); 

Output
World

Using for Loop (Custom Slicing)

If we want more control or need to slice in a more custom way, we can use a simple for loop.

JavaScript
let arr = [1, 2, 3, 4, 5];
let start = 1;
let end = 4;
let newArr = [];

// Loop through the array and manually add elements
for (let i = start; i < end; i++) {
    newArr.push(arr[i]);
}

console.log(newArr); // Output: [2, 3, 4]

Output
[ 2, 3, 4 ]

Using map() and filter() (Advanced)

For more complex slicing, we can combine map() and filter(). This method is less efficient for simple tasks but can be useful when combined with other logic.

JavaScript
let arr = [1, 2, 3, 4, 5];
let start = 1;
let end = 4;

let newArr = arr.filter((item, index) => index >= start && index < end);

console.log(newArr);

Output
[ 2, 3, 4 ]

Next Article
Practice Tags :

Similar Reads