- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Calculate the difference between the first and second element of each subarray separately and return the sum of their differences in JavaScript
We are required to write a JavaScript function that takes in an array of nested arrays that contains two elements each.
The function should calculate the difference between the first and second element of each subarray separately and return the sum of their differences.
For example− If the input array is −
const arr = [ [5, 3], [9, 4], [3, 7], [4, 6] ];
Then the output should be 1
Example
The code for this will be −
const arr = [ [5, 3], [9, 4], [3, 7], [4, 6] ]; const subtractAndAdd = (arr = []) => { let res = 0; for(let i = 0; i < arr.length; i++){ const [el1, el2] = arr[i]; res += (el1 − el2); }; return res; }; console.log(subtractAndAdd(arr));
Output
And the output in the console will be −
1
- Related Articles
- Calculating the average for each subarray separately and then return the sum of all the averages in JavaScript
- JavaScript Sum odd indexed and even indexed elements separately and return their absolute difference
- Difference between first and the second array in JavaScript
- Find difference between first and second largest array element in Java
- Difference between sum of the squares of and square of sum first n natural numbers.
- From an array of arrays, return an array where each item is the sum of all the items in the corresponding subarray in JavaScript
- Return the element that appears for second most number of times in the array JavaScript
- Difference between sum of square and square of sum in JavaScript
- The sum of two numbers is 1000 and the difference between their square is 256000. Find the numbers.
- Difference Between First level cache and Second level cache in Hibernate
- Return a subarray that contains all the element from the original array that are larger than all the elements on their right in JavaScript
- Calculate difference between circumference and area of a circle - JavaScript
- What are the differences between atom and element?
- Difference between sum and product of an array in JavaScript
- How to remove first array element in JavaScript and return it?

Advertisements