If you've worked with JavaScript, you'll know that arrarys are fundamental to your work as a developer and as such it would be helpful to manipulate an array with a few lines of code, rather trying some hack that you don't even understand.
Let's look at some array methods that makes working with arrays easier.
Slicing An Array
We can slice a part of an array, that is take away some part of an array and then do some manipulations on what we sliced away or what's left of the original array. The syntax is
array.slice(Start, end)
let myArr = [1, 2, 3, 4, 5, 6]
let slicedPart = myArr.slice(0, 3)
console.log(slicedPart)
//prints out [1, 2, 3, 4]
start is an integer that specifies where to start from and end is also an integer that specifies where to stop. It is to note that this method changes the original array and returns the sliced part as a new array.
ForEach
This method allows looping through arrays as simple as the alphabets instead of using a for loop, you should use For each. It accepts a callback function which takes a parameter that represents each item in the array. The syntax is
array.forEach((item)=>{
// do something with item
})
let myArr = [1, 2, 3]
myArr.forEach((item)=>{
console.log(item * 2)
//prints out 2, 4, 6
})
Map
This method allows us to return a new array from an existing array based on a condition, it takes a callback function that accepts an argument which represents each item in the array. It loops through the array and returns each element that passes the test. Although you could also modify each item instead of a test or return a property of the item. Syntax
array.map((item)=>{
//do anything with item
//e.g return item.name
})
var myArr = [{name: 'foo'}, {name : 'bar'}]
let newArrr = myArr.map((item)=> item.name)
console.log(newArrr)
//prints out ['foo', 'bar']
This method is useful for retrieving properties of objects stored inside an array.
Find an item
This function is useful for finding something inside an array without having to manually look inside it, it also accepts a callback function that we pass an argument, the argument represents each item in the array. Syntax
array.find((item)=> item = //anything)
var myArr = [{name: 'foo'}, {name : 'bar'}]
let obj = myArr.find((obj)=> obj.name == 'foo'
)
console.log(obj) //prints out
//{name: 'foo'}
Join
This method is used to join the contents of an array into a string. Syntax
let myArr = ['my', 'name', 'is', 'kala']
let myString = myArr.join(",")
console.log(myString)
//prints out
//my name is Kala
This method accepts a delimeter that is used to join the elements in the array.
IsArray
This method checks if an object is an array.
Array.isArray(obj)
//returns bool, true if an array
//false if not
let myArr = [1,2,3]
Array.isArray(myArr)
//true
Thank for reading this should make working with arrays easier for you.