#reduceRight() and #copyWithin()


It's a new JavaScript(2019) array function. This function is same as reduce() function with the feature that it start evaluating from right to left.

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


This is also a new JavaScript(2019) array function. This function has feature to copy array element inside itself and output is reflected on original array. I know its confusing about what I am saying, lets look into example

const array = [1,2,3,4,5];

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

  1. array.copyWithin(1), copy the all element of array and place this array from index 1.
  2. 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];
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);
  1. First Argument 1, denote copy array should be place from index 1.
  2. Second Argument 2, denote start copy elements from index 2. So copy items
    are 3,4,5
const array = [1,2,3,4,5];
console.log(array); // [1, 3,4,5,5]
#5 prints two times because after 3,4,5 no element is left
#so last 5 remain its position

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]

If you want to know more about JavaScript 2019 features then read this JavaScript 2019

Learn Something New Everyday,
Connect With The Best Developers!

Sign Up Now!

& 500k+ others use Hashnode actively.

No Comments Yet