#reduceRight() and #copyWithin()
const charArray = ['e','s','r','e','v','e','r']; const word = charArray.reduce((ac, c)=> ac+c); console.log('word is: ', word); // esrever
It starts evaluating from left and we get a string "esrever". Now if I want to evaluate this array from right so that my output is "reverse". This can be achieved by reduceRight()
const charArray = ['e','s','r','e','v','e','r']; const word = charArray.reduceRight((ac, c)=> ac+c); console.log('word is: ', word); // reverse
const array = [1,2,3,4,5]; array.copyWithin(1); console.log(array);
The output is [1,1,2,3,4]. array.copyWithin() this function copies your array elements and start place copy array from specified index. During the copy it will maintain the original size of the array. Consider the above example
- array.copyWithin(1), copy the all element of array and place this array from index 1.
- copy array is [1,2,3,4,5]. Original array size is 5. When it start placing element then it found that it extend the original size, so its ignore element 5.
const array = [1,2,3,4,5]; array.copyWithin(2); console.log(array); // [1,2,1,2,3]
We can also define from which element it should start copy.
array.copyWithin(place_index, start_from_index); array.copyWithin(1, 2);
- First Argument 1, denote copy array should be place from index 1.
- Second Argument 2, denote start copy elements from index 2. So copy items
const array = [1,2,3,4,5]; array.copyWithin(1,2); console.log(array); // [1, 3,4,5,5]
array.copyWithin(start_placing_index, start_from_index, end_index);
const array = [1,2,3,4,5]; array.copyWithin(2,3, 5); # start copy from index 3 to 5-1 index and start place from index 2 console.log(array); // [1,2,4,5,5]
3.4K+ developers have started their personal blogs on Hashnode in the last one month.
Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more