JavaScript Array Methods In ES6

Introduction

 
In this blog, we are going to learn about the new array functions, like flat(), flatMap(), reduceRight(), and copyWithin().
 

flat()

 
The flat() method creates a new array with all sub-array items merged into it up to specified depth.
 
Syntax
 
const flatArr = arr.flat([depth]) //depth will be specific up to what extent array needs to flatten.
 
Note: depth is optional
 
Example 1
  1. const arr=['a','b',['c','d']]  
  2. arr.flat(1)) or arr.flat()  
  3. //['a','b','c','d']  
Example 2
 
For a flat array of unknown depth:
  1. const arr =['a','b',['c',[[[[['d']]]]]]   
  2. arr.flat(Infinity)  
  3. //['a','b','c','d']   

flatMap()

 
The flatMap() method is the combination of map() and flat() functions. It will map all the elements of an array, then flatten those into a new array. 
 
Syntax
 
const flatMapArr = arr.flatMap(function callback(currentValue,Index,Array))
 
Note: currentValue= input array elements
 
Index= index of input array element(optional)
 
Array=it is used when array map is called(optional)
 
Example
  1. const arr1 = ['a','b','c']  
  2. const arr2 =[1,2,3]  
  3. arr1.flatMap((val,index)=>[val,arr2[index]]);  
  4. //['a',1,'b,2,'c',3]  

reduceRight()

 
The reduceRight() method reduces the array into a single value and executes the provided function on each item of the array (from right-left); the returned result from function is stored in the accumulator.
 
Syntax
 
array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
 
Note: function(total,currentValue, currentIndex,arr) Required.
 
initialValue is optional 
 
Example
  1. const arr1=['o','l','l','e','h']  
  2. arr1.reduceRight((c,v) =>c+v);  
  3. //"hello"   

copyWithin()

 
The copyWithin() method copies a specified part of an array to a specified location within the same array and returns it without changing the length.
 
Syntax
 
array.copyWithin(target,start,end)
 
Note:target: The index position to copy the elements to (required)
 
start: The index position to start copying elements from (optional)
 
end: The index position to stop copying elements (optional)
 
Example 1
  1. const arr1=['a','b','c','d']  
  2. arr1.copyWithin(0)   
  3. //['a','b','c','d']  
Example 2
  1. const arr1=['a','b','c','d']  
  2. arr1.copyWithin(2)  
  3. //['a','b','a','b']  
Example 3
  1. const arr1=['a','b','c','d']  
  2. arr1.copyWithin(0,3)  
  3. //['d','b','c','d']  
Note
 
These array functions are only supported in modern web browsers.