2

I have the following simple array:

my_array = [1, 11, 44, 4]

I want to produce a new array consisting of the difference between these elements, so it would be:

diff_array = [10, 33, 40]

What's the best way of going about this?

Babra Cunningham
  • 2,949
  • 1
  • 23
  • 50
  • You are seeking *the best way* but you are not showing your code. How will we compare if any of the approach is better than your's? – Rajesh Mar 20 '17 at 08:16

4 Answers4

6

You could use Array#reduce for iterating and take the absolute delta for pushing to the result array.

Basically you need array.length - 1 deltas and iteration. In this case 3. Reduce takes, if no start value is given, the first two elements and iterates the wanted length. And while it needs the last value for the delta, the last value is returned.

At the end, the returned value of reduce is discarded, becuase it is not used anymore.

1    11    44    4   values
 \  /  \  /  \  /
  10    33    40     Math.abs(delta)

var array = [1, 11, 44, 4],
    result = [];
    
array.reduce(function (a, b) {
    result.push(Math.abs(a - b));
    return b; 
});

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Could you explain why it works? Particularly the `return` statement. Thanks! – Mistalis Mar 20 '17 at 08:15
  • @Mistalis Please refer [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) and [how it works](http://stackoverflow.com/questions/5732043/javascript-reduce-on-array-of-objects) for explanation – Rajesh Mar 20 '17 at 08:17
  • This method is much slower than just loop through the array. – wdetac Mar 20 '17 at 08:39
  • @wdetac, a `for` loop is faster than *any* array method. – Nina Scholz Mar 20 '17 at 08:42
3

here is a simple solution with a plain old for loop

array = [1, 11, 44, 4]
diff = []

for(var i = 1 ; i < array.length ; i++){
  diff.push(Math.abs(array[i] - array[i-1]))
}

basically you loop starting at the second element of the array ,, and subtract from from the prev and pushing to the new array .

Ahmed Eid
  • 4,414
  • 3
  • 28
  • 34
2

use this function, pass it the input array, returns the required array.

function diff(array){
 var out = []
 for (var i = 0; i < array.length-1; i++) {
    out.push(Math.abs(array[i+1]-array[i]))
 }
 return out;
}
pranavjindal999
  • 2,937
  • 2
  • 26
  • 35
1

Normally one can do this with .reduce() but just for fun lets get some functional.

var myArray = [1, 11, 44, 4],
       diff = a => a.length > 1 ? [Math.abs(a[1]-a[0])].concat(diff(a.slice(1))) : [];

console.log(diff(myArray));

Note: The above code is just for demonstration purposes. In your daily JS life you shouldn't do things like this. Use a whatever loop you like but never use recursion in your JS code. You want to see what i mean? Feed this array.

var myArray = Array(1000000).fill().map(_ => ~~(Math.random()*100+1));

It will beautifully crash your browser's tab. Peah..!

Redu
  • 25,060
  • 6
  • 56
  • 76
  • This one is even faster then `for loop` method but somehow difficult to read. So it may not be the _best_. – wdetac Mar 20 '17 at 09:11
  • @wdetac I agree, JS itself becoming really schizophrenic. While the above code is very straightforward, unlike other languages, JS has many different ways to express the very same thing. You are not expected to know all of them. In Haskell you have a very strict syntax and certain ways of implementing your goal. In JS you have the while loop, for loop, recursion, functors, for in loop, for of loop i mean come on. You may perfectly well know JS and may have hard time read understand a simple code. It's not your fault it's JS trying to be both imperative and functional at the same time. – Redu Mar 20 '17 at 10:38
  • @wdetac BTW, I think the performance of this code is no where near `.reduce()`'s, set aside the for loops. Also in JS you should never use recursion with array operations unless you can guarantee the array length is very limited. In fact, in JS one should forget about recursion in total. It was just for fun :) – Redu Mar 20 '17 at 11:05