...

/

Array Transformations

Array Transformations

Learn about different array-related methods in JavaScript.

We will take the food array we created in the previous lesson and use some array-related methods on it.

food = ['Coconut', 'Pineapple', 'Melon', 'Burger', 'Fries', 'Cookie', 'Popcorn', 'Coffee' ]

Slicing and splicing

The slice() method creates a subarray, effectively chopping out a slice of an original array starting at one position and finishing at another. For example, if we wanted to find the third and fourth items in our food array, we would use the following code:

Press + to interact
console.log(food.slice(2, 4));

The first number in the parentheses tells us the index to start the slice at, and the second number tells us the index that the slice goes up to, without including that item. So in the example above, the slice will start at 'Melon', which has an index of 22, and then include all the items up to, but not including, the item with an index of 44, 'Fries'.

This operation is non-destructive, so no items ...