Wednesday, 12 December, 2018 UTC


Summary

Welcome to the second episode of the “Just so you know” series where we talk about Array Methods in JavaScript.
For those who are new here in this blog, this series talks about things that some of you might know or not. So now I’m going to introduce to you some rarely used Array Methods which the popular once are map, reduce and filter.
 
 
Reverse
We will start with one of the most simplest and useful method which is the reverse function which reverse the position of the array making the first array element becomes the last, and the last array element becomes the first.
const arr = [1, 2, 3, 4, 5];

console.log(arr.reverse()); // will produce [ 5, 4, 3, 2, 1 ]
Some of the use case of this method is when you have a sorted list of posts from oldest to latest and you need to display it on a table from the latest posts to the oldest. Also take note that be careful on using this as it mutates/reverse also the original array.
 
 
Every
every is used to check whether all elements in the array pass the test implemented by the provided function and would return a Boolean value.
const arr = [1, 2, 3, 4, 5];
const threshold = 10;

const isPassed = arr.every( item => item < threshold );

console.log(isPassed); // will return true
Just like the example, the use case of this method is that if you need to check all of the items of the array whether all of them meet your requirements or not.
 
 
Some
some is somewhat related with every however the difference is it only requires one to pass the test and not all of them.
const arr = [10, 24, 32, 4, 51];
const threshold = 10;

const isPassed = arr.some( item => item < threshold );

console.log(isPassed); // will return true
So like if you have a booking app and it needs to check whether the room still have an available time slot.
 
 
Shift & Unshift
If we have push and pop we also have shift and unshift which do the same thing but targets the first element of the array.
const arr = [1, 2, 3, 4, 5];
const newItem = 1;
arr.unshift(newItem);

console.log(arr); // [ 1, 1, 2, 3, 4, 5 ]

arr.shift();

console.log(arr); // [ 1, 2, 3, 4, 5 ]
This is one of the useful method when you want to make your newly created object into the beginning of your list.
 
 
Includes
includes is a method determines whether an array includes a certain element with the same type.
const arr = [1, 2, 3, 4, 5];
const intItem = 1;
const strItem = '1';

console.log(arr.includes(intItem)); // will return true
console.log(arr.includes(strItem)); // will return false
Going back with the booking app. includes can check if the specific time slot is available or not.
 
 
Reduce Right
reduceRight is same as reduce function but instead it starts iterating from right to left. so rather than using reverse then reduce, you could straight using reduceRight.
const arr = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (acc, cur) => acc.concat(cur)
);

console.log(arr); // [4, 5, 2, 3, 0, 1]
 
 
Copy Within
copyWithin method copies part of an array to the target index in the same array and returns it, without modifying its size.
var array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
array1.copyWithin(0, 3, 4); // ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
array1.copyWithin(1, 3); // ["d", "d", "e", "d", "e"]

// copy to index 2 the element at default target index which is 0
array1.copyWithin(2); // ["d", "d", "d", "d", "e"]
 
 
Flat (Experimental)
flat is still an experimental API that should not be used in production code but still worth the time to check because its very useful in the future if ever.
flat method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. The depth by default to 1 which flattens the first layer of nested arrays on the array.
const arr = [1, 2, [3, 4, [5, 6]]];
arr.flat(); // [1, 2, 3, 4, [5, 6]]
arr.flat(2); // [1, 2, 3, 4, 5, 6]


// You can use Infinity to flatten all the nested arrays no matter how deep the array is

const arrExtreme = [1, [2, [3, [4, [5, 6, 7, [8, 9]]]]]];
arrExtreme.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 
Extra
Do you know that doing for loop is more faster than map? So for having a large size array then a simple logic like adding one to every item. Let’s see the difference.
const arrayCount = 100000;

const arr = Array(arrayCount).fill(1);

console.time('map');

let mapResult = arr.map( item => item + 1 );

console.timeEnd('map');


console.time('forloop');

let forLoopResult = [];

for (let index = 0; index < arr.length; index++) {
    forLoopResult.push(arr[index] + 1);
}

console.timeEnd('forloop');
The results are:
//first test run
map: 17.296ms
forloop: 10.967

//second test run 
map: 16.788ms
forloop: 5.043ms

//last test run
map: 17.405ms
forloop: 4.446ms
reduce method has a similar output
const arrayCount = 1000000;

const arr = Array(arrayCount).fill(1);

console.time('reduce');

let reduceResult = arr.reduce( (item, acc) => item + acc );

console.timeEnd('reduce');


console.time('forloop');

let forLoopResult = 0;

for (let index = 0; index < arr.length; index++) {
    forLoopResult += arr[index];
}

console.timeEnd('forloop');
reduce vs forloop results:
reduce: 15.749ms
forloop: 3.250ms


reduce: 15.737ms
forloop: 3.171ms


reduce: 15.749ms
forloop: 3.079ms
Conclusion
In the end. its really the use case when to use this methods. if you have a pretty small set of data then its preferred to use this short and readable methods rather than using forloops however if we are talking about large amount of data and we need the best performance then maybe forloop would be your best bet.
To see more available Array Methods in JavaScript you could checkout this link.

For more “Just so you know” posts. Just click here

The post Just so you know: Uncommonly used Array Methods appeared first on Codedam.