There are many other array methods that can change arrays or create new ones based on the original array. The methods are shown below with their function as well as the syntax:
arrayname.reverse()
- reverses the elements of the current array
arrayname.join(separator)
- concatenates the elements with a separator and returns a string
arrayname.slice(fromIndex,toIndex)
- returns a new array containing the elements from indices fromIndex to toIndex (excluding toIndex)
- can be used to clone an array
arrayname.sort(function)
- sorts the items from the array, based on the function and returns a new array
arrayname.fill()
- fills an array with the given value and returns a new array
Let's go through these methods one by one. The first method, reverse()
reverses the array. This is why the array now starts with 10 instead 1. The next method, join()
creates a new string where each element is separated by the colon and two spaces. The slice method prints a new array consisting of the elements between index 0 and index 4. The sort()
method has its own function that sorts the array in ascending order, which is why the array changed from [10,9,8,…] to [1,2,3…]. The last method, fill()
, creates a new array with a length of 10, and fills the whole array with the character 'a'.
Edit Me on GitHub!