You'll learn:
Some useful array methods to make dealing with arrays is an easy thing, I hope you won't find any issues with handling arrays operations from now on.
Insert and Remove:
shift:
shift() is used to remove the first element of the array.
Array.shift()
unshift:
unshift is used to insert an element into the array, unshift will add the element to the start of the array
push:
push is used to append elements to the array, (add to the end)
pop:
pop is used to pop out (remove) the last element of the array
Sub-arrays:
slice:
slice is used to copy elements in a specific range.
e.g.you have an array and you want to get the elements between index 1 and index 3
when the end parameter is not defined, then the slice extends to the end of the array
let slicedArr2 = arr.slice(1)
// [2,3,4,5,6,7,8,9]
spliced:
slice is used to REMOVE elements from an array.
Reordering:
reverse:
used to reverse the array's elements.
sort:
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
You can fix this by providing a compare function.
so without compare function, sort() is not that useful.
more about sort:
Search and Sort:
includes:
used to check if an element does exist or not.
at:
simple, you pass an index and you get the value in that index.
indexOf:
indexOf() is the opposite of at(), you pass a value and get the value's index in the array.
sort:
sort can be used here as well
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
You can fix this by providing a compare function.
so without compare function, sort() is not that useful.
more about sort:
Adding and combining arrays :
concat:
used to combine (add together) two or more arrays, non of the combined arrays will be modified, concat() will return a new array instead.
Array to String conversion:
toString:
used to represent an array in string format.
there is also toLocalString(), search about it as an exercise and learn the difference between toString() and toLocalString(), if you know, please share the answer in a comment.
Other methods:
flat:
when you have a nested arrays and want to pull out all these nested arrays to a new array, flat() is used.
flat() doesn't modify the array, it returns a new array instead.
fill:
used to fill the whole or part of the array with a specific value.
References:
Thanks for reading, and feel free to ask any question about javascript or this series, and I appreciate any feedback to improve My content.
Find me on twitter, github and my portfolio.
Top comments (0)