Skip to content
Advertisement

Value differences inside an array [closed]

Let’s say I have this array:

Array_1 = [1,3,10,4];

I am trying to find the difference between adjacent elements within this array like this:

Array_2 = [ Array_1[0], Array_1[1]-Array_1[0], Array_1[2]-Array_1[1], Array_1[3]-Array_1[2] ];

In this case, it will be:

Array_2 = [1,2,7,-6]

How do I code this in JavaScript?

Advertisement

Answer

To answer your question:

So… the problem that is introduced from your initial question is that if you want to know the difference between any 2 numbers, it will always output 1 number… so for example 3 - 2 = 1. 2 numbers output 1 number. This means that when you have an array of n numbers, you will always have an output array of size n - 1. You specified the output in your problem given the input as [1, 3, 10, 4] should produce an output of [1, 2, 7, -6]. To make the input and output array have the same size, we have to address the case where we didn’t have enough input elements to obtain the output. So in the end, even with the "new" accepted answer (which does the same thing with less lines of code – but doesn’t highlight this issue), they had to address this situation… which is why you see arr[i - 1]||0 in their code. So the if / else statement could be read like this: if the index (i) minus 1 is greater than or equal to 0, subtract the elements normally, ie (n)th element minus (n-1)th element. Else, take the nth element and subtract 0 from it... Where technically, it would be undefined, because there wouldn't be enough input parameters to make sense of the subtraction function.

—Explanation—

To better understand this let us manually go over the loop:

Our array: [1, 3, 10, 4]

Steps in our Algorithm:

We define i to be the current index of our array we are at… we start at 0.

While i is less than the length of our array (4), let’s:

Check to see if i - 1 is greater than or equal to 0.

If it is not (which in the first pass, i is 0, so it is 0 – 1, which is not greater than or equal to 0), then (look at the else statement) we take the ith element (which is the 0th element) and subtract 1, and push it into the difference array (known as Array_2), which ends up as 1 - 0.

Then the loop increments i to 1.

i - 1 now is 0. When we check our if statement it passes so we take Array[1] – Array [0], which is 3 - 1 = 2.

We continue this process until i is greater than 3, but the loop won’t kick over to the next number, 4.

Array_1 = [1, 3, 10, 4];
Array_2 = [];

for (var i = 0; i < Array_1.length; i++)
{
  if (i - 1 >= 0)
  {
    Array_2.push(Array_1[i] - Array_1[i - 1])
  }
  else
  {
    Array_2.push(Array_1[i] - 0)
  }
}

console.log(Array_2)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement