JS array methods you should know (Part1)
Welcome back! We will continue to learn more about JS. If you
want to know more about about js read this. Today's topic is about arrays
and some important methods.
1-forEach
():
This method allows me to iterate through the array's
element.
The parameters is a function that will be called for
each element.
<pre> <code>
const nums = [ 1 , 2 , 3 , 4 , 5 ];
nums . forEach ( function ( x ) { console . log ( x )});
</code> </pre>
And the output is:
1 2 3
4 5
Personally, I prefer using the arrow function:
<pre> <code>
const nums = [ 1 , 2 , 3 , 4 , 5 ];
nums . forEach (( x , index ) => console . log ( "nums [" + index + "] =" + x ));
</code> </pre>
And try to guess the output on your own.
This method is very useful to apply operations to each element.
Know use it to multiply each number by 2.
2 -map ():
This method execute a given function on each element and return an
array. Don't get confused with ForEach. Because ForEach doesn't
retrun an output it just loop trough the array.
<pre> <code>
const products = [
{ name: 'A' ,cost: 300 , discount: 0.3 },
{ name: 'B' ,cost: 500 , discount: 0.25 },
{ name: 'C' ,cost: 100 , discount: 0.4 }
];
const newProducts = products . map( product => (
{ name : product . name ,
cost : product . cost * ( 1 - product . discount )
}));
console . log ( newProducts );
</pre> </code>
Well, as you see I have created an array of products. and using
map I will create another containing cost
after discounts.
The product is an iterator of type object. then for each object it
will return another object using the product attributes. After mapping
through the array. We will get out new one.
Trying running it and see the output.
Bonus: map is faster than forEach.
3-filter():
This method return an array where all the element respect a certain
conditions. So let's try to get only the even number from an array.
<pre> <code>
const nums =
[ 1 , 2 , 3 , 4 , 5 , 6 ];
const evenNums = nums . filter ( x => x % 2 === 0 );
console . log ( evenNums );
</pre> </code>
As you see the result is:
[2, 4, 6]
This method is very useful to get specific range or type of data.
Now try to create an array of object (person) with 2 attributes: name
and age. Then use the filter method to get adults array with age> 18.
Solution:
<pre> <code>
const persons = [
{ name: "john" , age: 34 },
{ name: "albert" , age: 14 },
{ name: "sarra" , age: 10 },
{ name: "lise" , age: 50 },
];
const adults = persons . filter ( p => p . age > = 18 );
</pre> </code>
4-reduce():
This method will execute a function on each array element and it will
return a single element. The best use case here is calculating the sum of
array number. We use a function with 2 parameters:
Y: the accumulator. It's where we keep track of the result;
X: representing the value of each element
And the 0 as an initial value of y.
<pre> <code>
const nums =
[ 1 , 2 , 3 , 4 , 5 , 6 ];
const sum = nums .reduce (( y , x ) => y + x , 0 );
console . log ( sum )
</pre> </code>
And the result is: 21
Another example is getting the max or the min value of an array.
Before seeing the solution try to think of it a little.
<pre> <code>
const nums =
[ 11, 2 , 31 ,
- 4 , 51 , 6 ];
const min = nums . reduce (( y , x ) =>y > x ? x : y , Infinity );
const max = nums . reduce (( y , x ) => y < x ? x : y,
- Infinity );
console . log ( max , min )
</pre> </code>
Ok let's explain now! the y is initialized to infinity. Which
is the biggest number. So each time we loop through values
we compare the y by x. if y> x than y = x (return
x) and so on. When we finish we return y. in this
case it will take the minimum value! The same goes the second one.
5-slice ():
It returns a copy from original array without touching it. Given
it the index of the beginning and the end, or only the beginning.
<pre> <code>
const nums =
[ 11 , 2 , 31 ,
- 4 ,51 , 6 ];
const nums2 = nums .slice ( 1 , 5 );
const nums3 = nums . slice (- 1);
const nums4 = nums . slice ( 1 );
console . log( nums2 );
console . log( nums3 );
console . log( nums4 );
</pre> </code>
Just Note: the -1 stand for the last element. and the created array
will stop at element before the ending index.
Next article, we will talk about other method. Hope you liked.
No comments