- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What should be the correct Algorithm to Get Array B from Array A counting backwards from the last element in JavaScript?
Consider the following binary array (Array A) −
const arr = [1,0,1,1,1,1,0,1,1];
When this array is passed through the function, say sumRight(), it produces the following output array (Array B) −
const output = [1,0,4,3,2,1,0,2,1];
Understanding the function
Elements in array arr can be either 0 or 1. The function counts backward from the last element of array arr, if there are consecutive 1's in the array arr then the corresponding element in the output array will be 1 but for the 2nd consecutive 1 in array arr, it will be 2. For the 3rd one in input array the element in the output array will be 3, but for 0 in the array arr it will be 0 in the output array as well.
So let’s write the code for this function using the Array.prototype.reduceRight() method, which does the same work as the normal reduce method, it just starts from the right instead of left −
Example
const arr = [1,0,1,1,1,1,0,1,1]; const sumRight = arr => { return arr.reduceRight((acc, val) => { const { prev, res } = acc; if(val === 0){ return { prev: 0, res: res.concat(0) }; }; return { res: res.concat(val+prev), prev: prev+1 }; }, { prev: 0, res: [] }).res.reverse(); }; console.log(sumRight(arr));
Output
The output in the console will be −
[ 1, 0, 4, 3, 2, 1, 0, 2, 1 ]