Computer >> Computer tutorials >  >> Programming >> Javascript

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