DEV Community

Randy Rivera
Randy Rivera

Posted on

Returing Part of an Array Using the slice Method

  • The slice method as we have already learned about returns a copy of certain elements of an array. It can take two arguments, the first gives the index of where to begin the slice, the second is the index for where to end the slice (and it's non-inclusive). If the arguments are not provided, the default is to start at the beginning of the array through the end. The slice method does not mutate the original array, but returns a new one.

  • Here's an example:

var myarr = ["PS5", "Switch", "PC", "Xbox"];
var myConsoles = myArr.slice(0, 3);
Enter fullscreen mode Exit fullscreen mode
  • myConsoles would have the value ["PS5", "Switch", "PC"].

  • Alright then let's use the slice method in the sliceArray function to return part of the anim array given the provided beginSlice and endSlice indices. The function should return an array.

function sliceArray(anim, beginSlice, endSlice) {
  // Only change code below this line


  // Only change code above this line
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function sliceArray(anim, beginSlice, endSlice) {
return anim.slice(beginSlice, endSlice);

}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
console.log(sliceArray(inputAnim, 1, 3)); will display ['Dog', 'Tiger']
Enter fullscreen mode Exit fullscreen mode

Larson, Quincy, editor. β€œReturn Part of an Array Using the slice Method.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.

Top comments (0)