Hello everyone! I hope everyone is safe and being productive in this quarantine period properly. Investing time in building up knowledge now, Will help you in the latter time.
Well, let's stop complaining about being stuck and let's invest this time in building ourselves.
Now, since we have some perspective of arrays its time to manipulate our array. As we know array is a list-like structure, we must be using arrays for storing multiple values. Now we do need to iterate through the values in the array.
A most common way used in all programming languages is to use for loop. Using for loop we iterate through each element in the loop.
Consider the example below, here we have a fruits array or basket of fruits (intentionally derived from my first blog😉). I have lots of fruits in my basket and I want to iterate through them
Array.filter(callback(currentValue [, index [, array]][, thisArg])) function iterates through an array and returns a new array of values that passes the condition. Callback represents a function that checks for condition and returns a new array of values that fulfills condition.
Here, I am filtering fruits that are lexicographically greater than 'banana'. Since 'apple' (a is less than b) is lexicographically smaller than 'banana' we get all the fruits except 'apple'.
Array.find(callback(currentValue [, index [, array]][, thisArg])) function is similar to filter function except that find function return a variable fulfilling condition. Callback represents a function that checks for condition and returns the first value from the array that fulfills the condition.
Here, I am using find function to filter fruits that are lexicographically greater than 'banana'. Since 'mango' (left to right) is the first element in the array that is lexicographically greater than 'banana' we get 'mango'.
Array.forEach(callback(currentValue [, index [, array]][, thisArg]) function is similar to foreach loop, iterate over all the values of array. The callback function specifies the operation to be applied once on each value of the array and returns an undefined value. Unlike Array.map and Array.reduce function forEach function always returns an undefined value and they are not chainable.
Here, I am simply console logging each element in the array. The callback function returns an undefined value.
Now we have more ways to iterate through an array, each serving a different purpose. Hope this post was helpful!