JavaScript Array Methods In ES6

This blog gives a brief explanation of the new array functions, like flat, flatMap, reduceRight, and copyWithin().

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


The flat() method creates a new array with all sub-array items merged into it up to specified depth.
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']   


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. 
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)
  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]  


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.
array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
Note: function(total,currentValue, currentIndex,arr) Required.
initialValue is optional 
  1. const arr1=['o','l','l','e','h']  
  2. arr1.reduceRight((c,v) =>c+v);  
  3. //"hello"   


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.
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']  
These array functions are only supported in modern web browsers.