Top 5 JavaScript Array Methods To Access Through Elements

Share this post

Top 5 JavaScript Array Methods To Access through Elements

apps javaScript Array Methods

 

Hello everyone. Yet again we bring the JavaScript Array methods for you, this time top 5 javaScript array methods like forEach(), map(), every(), reduce(), sort(). Read till last as there is a simple challenge for you to test your skills and many more to learn.

First talk about the Javascript Challenge#1, which I asked you all in our first lesson on JavaScript Array Methods for basics. If you didn’t read, click on the link below and read it, so you will have a good idea about other important JavaScript arrays methods.

“JavaScript Array to make our life easy – Under the Hood Concepts”

Solution for JavaScript Challenge#1 as below,

var months = ["January", "February", "March", "April", "May", "June", "July", 
                     "August", "September", "October", "November", "December"]

const monthsNew = months.filter((month) => month.length > 6);

console.log(monthsNew); // ['January','February','September','October','November','December']

Let’s start today’s lesson. Today we will discuss, mostly used javaScript methods which are very useful when we work with Arrays.

forEach/ map /every

These JavaScript array methods are quite similar in nature and syntax. All of them work through each element of the parent array.

Their syntax is same as other methods like filter(), find(), findIndex(), some() which we discussed in the last lesson.
array.forEach(callback(element, index (optional), array(optional)), this);

array.map(callback(element, index (optional), array(optional)), this);

array.every(callback(element, index (optional), array(optional)), this);

First Parameter: callback function which sets the search condition. this function takes 3 arguments

  1. current element of the parent array which is going to be processed
  2. index number (Optional) of the current element.
  3. array (Optional) the parent array itself on which method going to be processed

Second Parameter (Optional): It is the “this” argument that can be used while performing the callback function. This is also an optional parameter. This parameter to use when we want to use the callback function value at the same time. By default it is undefined.

Let’s discuss each of them one by one.

forEach()

This array method very easy to find every time you start working on any critical projects. This is one of the most used array methods.

This method allows you to work on each element of an array. Suppose if you want to print all elements one by one from an array, you can use this method. let’s see from an example

var apps = [ 'Google',  'Amazon',  'Microsoft',  'Facebook',  'WhatsApp',  
                                            'Instagram',  'PayPal']
apps.forEach((e) => console.log(e));

//google
//amazon
//microsoft
//facebook
//whatapp
//instagram
//paypal
In the above example, forEach() runs through each element in the apps array and prints it into the console. Although It does not impact or mutate its parent array, you can write the function which can manipulate the parent array. Example
var apps = [ 'Google',  'Amazon',  'Microsoft',  'Facebook',  'WhatsApp',  
'Instagram',  'PayPal'];

apps.forEach((e) => { 
                       apps.push(e.toUpperCase());
                    });

console.log(apps);

/* 
['google', 'amazon','microsoft', 'facebook','whatapp', 'instagram','paypal', 'GOOGLE',
'AMAZON', 'MICROSOFT','FACEBOOK', 'WHATAPP','INSTAGRAM', 'PAYPAL']   
*/
As we see the above example, we used push() method to add all the capitalized apps inside the parent array itself. One last thing about this method, it always returns undefined.
var anyValue = apps.forEach((e) => {
  return 1;
});

console.log(anyValue);  // undefined

Our next JavaScript Array method is map(). It works the same as forEach() with a little difference. Let’s see

map()

As I mentioned above, this method works the same as forEach(), but it returns a new separate array with the same number of elements its parent array has. It also not affect or mutates any element of its parent array.

Note: If you do not want to use the array which returned from the map() method, you should use forEach() instead of map().

Let’s see the examples

var apps = [ 'Google','Amazon','Microsoft','Facebook','WhatsApp','Instagram','PayPal'];

var letSee = apps.map((e) => {
  return e.length > 7;
});

// It will go through all the elements in the parent array (apps) and return the value 
according to our condition

console.log(letSee);    //[false, false,true,true,true,true,false]

//Another Example

const prime = [2, 3, 5, 7, 11, 13, 17, 19];

var remainder = prime.map((e) => {
  return e % 2;
});

//It will go through all element and check what is the remainder and return a separate
array with all the remainder

console.log(remainder);  //[0,1,1,1,1,1,1,1]

We can also combine little complex conditions for the return value. let’s see in the above example.

var apps = ['Google','Amazon','Microsoft','Facebook','WhatsApp','Instagram','PayPal'];

var letSee = apps.map((e) => {
  if (e.length > 7) {
    return e;
 }
});
console.log(letSee);   //[undefined,undefined,‘Microsoft’,‘Facebook’,‘WhatsApp’,
‘Instagram’,undefined]

In the above example, the function runs through each element and check if element length is more than 7. if this condition true, return the element itself. but we didn’t define what to do if the condition is false. that’s why it returned undefined.

every()

This method also works through all the elements in an array and returns true or false according to the provided condition. If all the elements follow the condition it will return true but if any one of the elements does not follow the given condition, it will return false. Let’s see with the help of example

var apps = [ 'Google','Amazon','Microsoft','Facebook','WhatsApp','Instagram','PayPal'];

var letSee = apps.every((e) => {
                                  return e.length > 7;
                               });

console.log(letSee);     //false
var letSeeOnceAgain = apps.every((e) => {
                                          return e.length > 5;
                                        });

console.log(letSeeOnceAgain);   //true

In the above example, all the elements have more than 5 characters that’s why the second method call returned true but the first method call returned false as not all the elements have more than 7 characters.

reduce()

This method runs through each element of the array, process a function, and return a single value. It does not affect or mutate its parent array. Its syntax

array.reduce(callbackFunction(total,currentValue,currentIndex,array),initialValue)

This method takes two parameters. First is a callback function and the second is the initial value.

First Parameter: callback function which executes on each element of the parent array. this function takes 4 arguments

  1. accumulator or total: it is the value that keeps accumulated or adding after each execution
  2. current value: It is the current element which is being processed in the array
  3. Index(Optional): It is the index number of the current element
  4. array (Optional): It is the array itself.

The last two are optional arguments for the callback function.

Second Parameter (Optional): the initial value is the value we provide as an accumulator for the first callback execution. As this is optional, if we not provide this parameter after the first execution accumulator value will be the first element of the array.

var num = [1, 3, 5, 7, 9, 11];

var total = num.reduce((a, b) => {
                                  return a + b;
                                 }, 100);
var anotherTotal = num.reduce((a, b) => {
                                 return a + b;
                                 });

console.log(total);    // 136

console.log(anotherTotal); // 36

let’s see what happened in the above example:

JavaScript array reduce method

first, we assign accumulator initial value= 100 and the first element of the array is 1. So for our callback function a = 100, b=1. When it executed callback function for the first time a = 100+1 = 101 and b = 3 as the second element. Then for 3rd step a = 101+3 = 104 and b = 5 as third element of array and so on. After the sixth step of the execution, it returns 136, which is our final accumulator or the return value from the reduce() method.

sort()

This method one of the top 5 javaScript arrays methods which sort the elements inside an array in ascending or descending order. This method does not return any new array or value instead it mutates or sort inside the parent array itself. By default, It sorts the element based on a string no matter if your array has numbers or any other primitive type.

so if we sort (“john”, “rocky”, “mark”) in ascending order,  it will return “john” < “mark” < “rocky”. Similarly, if we sort “120”,”90″,”400″,”25″,”3″,”11″ in ascending order, it will return “11”<“120″<“25″<“3″<“400″<“90”. Let’s see in the actual code

var name = ['john', 'rocky', 'mark'];
var numbers = [120, 90, 400, 25, 3, 11];
name.sort();
numbers.sort();

console.log(name);     //[ 'john', 'mark', 'rocky' ]
console.log(numbers);  //[ 11, 120, 25, 3, 400, 90 ]

So, this is what we don’t want for numbers at least. W e have the solution for this. Let’s See the syntax

array.sort(comparingFunction(a, b))

Parameter (Optional): comparing function, this parameter we provide to tell the conditions for sorting so that we get the actual result which we want. This function also has two parameters which is being compared.

array.sort(function(a,b){return a-b})   // for ascending order

OR

array.sort(function(a,b){return b-a})   // for descending order

Example:

var numbers = [120, 90, 400, 25, 3, 11]

numbers.sort((a, b) => a - b);

console.log(numbers);     // [ 3, 11, 25, 90, 120, 400 ]

numbers.sort((a, b) => b - a);

console.log(numbers);     //[ 400, 120, 90, 25, 11, 3 ]

These are the top 5 JavaScript Array methods about accessing the array elements. If you have any questions regarding this topic or any other javaScript topics please mention in the comment, so that I can promptly reply to you. And if you have not read our previous lessons of JavaScript Array, just click the link below and read it.

JavaScript Tutorial lessons

you can also visit MDN website for more details.

JavaScript Challenge#4

Now, time for yet another javaScript challenge for you. I want to know if every element in the array “numbers” are even numbers or not. Use any of the methods I explained in this lesson above, which suits best for this challenge. Write your answers in the comment box. I will reply to you there, Let’s see who will be correct. Also if you can’t get the answer, don’t worry as you can check the answer in the link below.

var numbers= [2,5,97,58,48,36,45,79,63,59,5,22,60];

JavaScript Global Execution Context – Behind the Scene

We will come again with some more knowledge very soon. Sign up with us so that you will not miss any of the future articles in the sequence of JavaScript tutorials. You can also follow us on our twitter or Facebook pages for all the future Lessons.

If you’re interested, Check out some other articles related to present crisis Coronavirus

Take care of yourself and your family!♥

Leave a Comment

Your email address will not be published. Required fields are marked *