How to use JavaScript Array slice method?

 JavaScript Array slice() Method return a new array according to given argument, 

we can pass two argument start point and end point(means till).


Syntax is the : array.slice(start, end)

Start end means this is number of index and end not includes in the index. as given below example.


Array slice method examples:

const colors = ['red', 'green', 'blue', 'pink', 'purple', 'orange', 'aqua'];

 

console.log(colors.slice(4)); 

// output: Array ["purple", "orange", "aqua"]

 

console.log(colors.slice(4, 6));

// output: Array ["purple", "orange"]

 

console.log(colors.slice(1, 6));

// output: Array ["green", "blue", "pink", "purple", "orange"]

 

console.log(colors.slice(4, 4));

// output: []

 

console.log(colors.slice(4, 8));

// output: ["purple", "orange", "aqua"]

 

//Slice also work with negative value as below example

 

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

 

console.log(fruits.slice(-1));

// output: Array ["Mango"]

 

console.log(fruits.slice(-3));

// output: Array ["Lemon", "Apple", "Mango"]

 

console.log(fruits.slice(-1, -1));

// output: Array []

 

console.log(fruits.slice(-1, -3));

// output: Array []

 

console.log(fruits.slice(-4, 4));

// output: Array ["Orange", "Lemon", "Apple"]


 

No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.