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
- const arr=['a','b',['c','d']]
- arr.flat(1)) or arr.flat()
-
Example 2
For a flat array of unknown depth:
- const arr =['a','b',['c',[[[[['d']]]]]]
- arr.flat(Infinity)
-
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
- const arr1 = ['a','b','c']
- const arr2 =[1,2,3]
- arr1.flatMap((val,index)=>[val,arr2[index]]);
-
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
- const arr1=['o','l','l','e','h']
- arr1.reduceRight((c,v) =>c+v);
-
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
- const arr1=['a','b','c','d']
- arr1.copyWithin(0)
-
Example 2
- const arr1=['a','b','c','d']
- arr1.copyWithin(2)
-
Example 3
- const arr1=['a','b','c','d']
- arr1.copyWithin(0,3)
-
Note
These array functions are only supported in modern web browsers.