Basic Data Structures: Copy Array Items Using slice()

Basic Data Structures: Copy Array Items Using slice()
0

#1

Guys I have a question.

Following the array index, to find, add or remove an element it should be like this isn’t?
image

in this code, it is behaving differently which is tricking my mind.

let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];

//>>>>WHY (1,3) IS RETURNING ['snow', 'sleet']; AND NOT ['rain', 'sleet', ]<<<< ????

let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather equals ['snow', 'sleet'];
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']

thank you.


#2

The first argument passed to the slice method defines the starting point of extraction. In this case, 1 is the 2nd element ‘snow’, because arrays are zero-indexed. The second argument passed to the slice method defines the index before which to end extraction. The slice extracts up to but not including this index. In this case, the 3 represents the index of the 4th element, so we extract up to but do not include the 4th element. This means ‘sleet’ is the only other extracted element (after ‘snow’) in this particular slice.