Javascript Array Slice Method

javascript-array-slice-method

The slice method on arrays returns a shallow copy of a part of an array. It takes two numbers, a start, and an end. Every array has a slice method. Here is a quick example:

let myArray = [ '⚡️', '🔎', '🔑', '🔩' ];
let newArray = myArray.slice(2, 3);

console.log(newArray); // [ '🔑' ]

There are two optional parameters for the slice method, start, and end. You can provide both, only start, or neither, if you like – so all of these are valid:

let arrayOne = [ '⚡️', '🔎', '🔑', '🔩' ];
let arrayOneSlice = arrayOne.slice(2, 3);  // [ '🔑' ]

let arrayTwo = [ '⚡️', '🔎', '🔑', '🔩' ];
let arrayTwoSlice = arrayTwo.slice(2);  // [ '🔑', '🔩' ]

let arrayThree = [ '⚡️', '🔎', '🔑', '🔩' ];
let arrayThreeSlice = arrayThree.slice();  // [ '⚡️', '🔎', '🔑', '🔩' ]

start

This is the index of the first item to include in your new array. For example, if set to 2, the slice will start your new array copy at index 2. If a negative is used, it indicates offset from the end of a sequence. For example:

let arrayOne = [ '⚡️', '🔎', '🔑', '🔩' ];
let arrayOneSlice = arrayOne.slice(-2);  // [ '🔑', '🔩' ]
let arrayOneSliceAgain = arrayOne.slice(-1);  // [ '🔩' ]

end

This is the first element to exclude from your sliced array – which is kind of confusing. You might expect end to represent the last item to include – but instead it is the first item to exclude. Keep that in mind if you use slice! If you omit this argument, the slice method will simply continue to the end of the array, as shown in this example:

let arrayTwo = [ '⚡️', '🔎', '🔑', '🔩' ];
let arrayTwoSlice = myArray.slice(2);  // [ '🔑', '🔩' ]

If a value greater than the array length is used, slice only continues to the end of the array. If a negative value is used, it indicates an offset from the end of an array. For example, (2, -1) will go 2 from the start, and -1 from the end of an array:

let arrayOne = [ '⚡️', '🔎', '🔑', '🔩' ];
let arrayOneSlice = arrayOne.slice(2, -1);  // [ '🔑' ]
let arrayOneSliceAgain = arrayOne.slice(1, -1);  // [ '🔎', '🔑' ]

Using slice to make a copy of an array

Slice does not mutate the original array. It instead creates a new shallow copy. As such, your existing array will still continue to contain the same values:

let arrayOne = [ '⚡️', '🔎', '🔑', '🔩' ];
let arrayOneSlice = arrayOne.slice(2, 3);  

console.log(arrayOne); // [ '⚡️', '🔎', '🔑', '🔩' ]
console.log(arrayOneSlice); // [ '🔑' ]

Since slice makes a shallow copy of an array, it is also sometimes used to duplicate and make copies of your array data. For example, an empty slice function will also create a new array in memory – allowing you to have two copies of the same array with the same reference in memory:

let arrayOne = [ '⚡️', '🔎', '🔑', '🔩' ];
let arrayOneSlice = arrayOne.slice();

arrayOneSlice[2] = '⚡️'
console.log(arrayOne); // [ '⚡️', '🔎', '🔑', '🔩' ]
console.log(arrayOneSlice); // [ '⚡️', '🔎', '⚡️', '🔩' ]

This can be useful in some scenarios. However, slice only makes a shallow copy of an array. That means things get a little confusing when you have objects in your array. Consider the following array:

let arrayOne = [ { items: [ '⚡️', '🔎', '🔑', '🔩' ]}, '👨‍💻', '😄', '🐔' ]

This array contains an object within it. Let’s try making a sliced copy of this array, and then update items:

let arrayOne = [ { items: [ '⚡️', '🔎', '🔑', '🔩' ]}, '👨‍💻', '😄', '🐔' ]
let arrayOneSlice = arrayOne.slice(0, 2);

arrayOneSlice[0].items = [ '🔎' ];
arrayOneSlice[1] = '🔎';

console.log(arrayOne); // [ { items: [ '🔎' ]}, '👨‍💻', '😄', '🐔' ]
console.log(arrayOneSlice); // [ { items: [ '🔎' ]}, '🔎' ]

Wait, what? We changed arrayOneSlice‘s items object, but its changed in both arrayOne and arrayOneSlice! Meanwhile, arrayOneSlice[1] has only changed arrayOneSlice! Welcome to another Javascript quirk. In the first example, using the arrayOneSlice[0].items notation, Javascript interprets this as updating an existing element within the shallow copy and thus it affects the original. However, somewhat confusingly, by using the arrayOneSlice[1] notation, Javascript interprets this as putting a new value into the [1] place of the shallow copy itself.

That means that although it may seem like you are making a copy with slice when working with simple arrays, this does not hold up when using it on more complex objects. Knowing this little piece of trivia is going to save you a lot of time someday.

Conclusion

The Javascript slice method is useful for creating new shallow copies of arrays with a subset of the original arrays data. It can also be used in a limited way to make duplicates that can be independently updated. Javascript slice copies still have the same reference as the original in memory, which is useful to know when manipulating them.

I hope you’ve enjoyed this guide. For more Javascript, check out my other articles here.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
how-to-change-a-git-commit-date-(for-beginners)

How to Change a Git Commit Date (For Beginners)

Next Post
react,-the-humble-–-write-once,-render-in-web-and-native

React, the Humble – Write once, render in Web and Native

Related Posts
arkui-x平台差异化

ArkUI-X平台差异化

跨平台使用场景是一套ArkTS代码运行在多个终端设备上,如Android、iOS、OpenHarmony(含基于OpenHarmony发行的商业版,如HarmonyOS Next)。当不同平台业务逻辑不同,或使用了不支持跨平台的API,就需要根据平台不同进行一定代码差异化适配。当前仅支持在代码运行态进行差异化,接下来详细介绍场景及如何差异化适配。 使用场景 平台差异化适用于以下两种典型场景: 1.自身业务逻辑不同平台本来就有差异; 2.在OpenHarmony上调用了不支持跨平台的API,这就需要在OpenHarmony上仍然调用对应API,其他平台通过Bridge桥接机制进行差异化处理; 判断平台类型 可以通过let osName: string = deviceInfo.osFullName;获取对应OS名字,该接口已支持跨平台,不同平台上其返回值如下: OpenHarmony上,osName等于OpenHarmony-XXX Android上,osName等于Android XXX iOS上,osName等于iOS XXX 示例如下:…
Read More