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()
- //['a','b','c','d']
Example 2
For a flat array of unknown depth:
- const arr =['a','b',['c',[[[[['d']]]]]]
- arr.flat(Infinity)
- //['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
- const arr1 = ['a','b','c']
- const arr2 =[1,2,3]
- arr1.flatMap((val,index)=>[val,arr2[index]]);
- //['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
- const arr1=['o','l','l','e','h']
- arr1.reduceRight((c,v) =>c+v);
- //"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
- const arr1=['a','b','c','d']
- arr1.copyWithin(0)
- //['a','b','c','d']
Example 2
- const arr1=['a','b','c','d']
- arr1.copyWithin(2)
- //['a','b','a','b']
Example 3
- const arr1=['a','b','c','d']
- arr1.copyWithin(0,3)
- //['d','b','c','d']
Note
These array functions are only supported in modern web browsers.
Ayush AgarwalPosted Sep 3, 2019, 7:14 AM
That was really helpful thanks
Mahesh ChandPosted Jun 19, 2019, 9:08 AM
Thank you Girish. Welcome to C# Corner
Madan ShekarPosted Jun 19, 2019, 8:56 AM
Nice information....