Must know Array Methods for developer, Holy Grail of JavaScript Application
Array has been around for a long time and has many methods that are useful for developers. JavaScript Array is quite different from the typed language (Java) , they are resizable and can contain a mix of different data types.
This article will go through the top most important JavaScript methods, and its hidden details.
1. reduce()
This is one of most underrated method due to its nature, it difficuilt to understand but once you know its behavior, it will solve complex problem like A B C Japaneasy.
The reduce() method accepts two parameters the reducer function and initial value which is optional.
the reducerFn have two parameters accumulator and currentValue
which will execute untill all the elements are processed.
If the initialValue is suppiled by the caller then accumulator will have the initialValue and currentValue will have the first value(zero index).
If no initialValue is provided then accumulator will have the first Value and currentValue will have the second value.
Example 1 : (No initial Value)
Example 2: With initial Value as 2
2. filter()
create shallow copy of a portion of a given array, filtered down to just the element from the given array that pass the test.
3. find()
method return the first element in the provided array that satisfied the provided testing function. If no values satisfy the testing function, else undefined is returned.
4. join()
method creates and returns a new string by concatenating all of the elements in an array separated by commas or a specified separator string.
5.flat()
flat(depth?) — method creates a new array with all sub-array elements concatenated into it recursively upto the specified depth.
6.Array.from()
This is a static method, which return a new array with shallow copies of Array instance from an iterable or array like objects
sometime this method is useful check this use case, if you want to modify attribute of any similar DOM object, here is an example
There are a number of Array methods in JavaScript allowing to choose the right method. You can play with data structure and algorithms. When it is there, you have benefits. You can focus on your business logic development rather than implementing our own method. So, it reduces your development efforts and reduced effort for code maintenance.
The array method, when used appropriately, can be a powerful tool to quickly and elegantly solve many programming problems. It is a general-purpose tool that is applicable in all sorts of situations.