Introduction
JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with
JavaScript.
Before moving further let us look at the previous articles of the series:
New Array methods were introduced, and widely used now. I find these extremely useful and many modern JS libraries are heavily dependent on these, e.g., UnderscoreJS
We’ll look at commonly used Array methods
Map
The map() method creates a new array with the results of calling a function for every array element.
Parameters
Callback- produces an element of the new Array & runs over each element
- currentValue- current element being processed
- index- index of the current Array element
- array- array map was called upon
- var numbers = [1, 2, 3, 4];
- var ary1 = numbers.map(function(item, index) {
- return item * 2;
- });
- console.log(ary1);
Therefore, the above code leverages Map method & iterates over each item and produces a new Array containing product by 2. The index is optional to pass & you could use inside callback function (item, index)
Reduce
The reduce() method reduces the array to a single value.
Parameters
A callback function runs on each value and takes four arguments:
- previousValue- value returned previously
- currentValue- current element being processed
- index- index of the current Array element
- array- array map was called upon
Example
- var numbers = [1,2,3,4];
- var total=numbers.reduce (function (prev,current) {
- return prev+current;
- });
- console.log(total);
Look at stack trace where prev & current values could be debugged. This method processes two values at a time.
Filter
It creates a new array with all elements which pass the test.
Parameters
Callback- to test each element of the array. It returns true to keep the element, false otherwise.
- var numbers = [1,2,3,4];
- var ary1 = numbers.filter (function (value) {
- return value > 2;
- });
- console.log (ary1);
Find
It returns a value in the array if it’s found, otherwise undefined is returned.
Parameters
Callback- to test each element of array.
- element- current processed value.
- index- index of current Array element.
- array- array map was called upon.
- var numbers = [1,2,3,4];
- var value = numbers.find (function (element) {
- return element == 2;
- });
- console.log(value);
Every
The purpose of this method is to iterate over each element of an Array and validate for all elements. Here is the syntax from VSCode.
Example
- function isPrime(number) {
- var start = 2;
- while(start <= Math.sqrt(number)) {
- if(number % start++ < 1) return false;
- }
- return number > 1;
- }
- var numbers = [3, 5, 7];
- var flag = numbers.every(isPrime);
- console.log(flag);
Summary
Please use these methods as it simplifies your code and reduces your time in these operations.