fandiahm
fandiahm

Reputation: 113

Javascript how to calculate values inside array?

I have this array :

arr = ["003448", "003609", "003729", "003800", "004178", "004362", "004410"];

I want to convert it become like this :

new_arr =  [161, 120, 71, 378, 184, 48];

161 result from 003609 - 003448

120 result from 003729 - 003609

and so on..

The rule is "The next value will be reduced by previous value". I have no clue with this. Anyone please help me.. I will be highly appreciate.

Upvotes: 1

Views: 125

Answers (3)

rgthree
rgthree

Reputation: 7273

Your question seems to scream Array.reduce:

var arr = ["003448", "003609", "003729", "003800", "004178", "004362", "004410"];
var new_array = arr.reduce(function(a, currentValue, currentIndex, array) {
  var previousValue = array[currentIndex - 1];
  if (previousValue !== undefined)
    a.push(parseInt(currentValue, 10) - parseInt(previousValue, 10));
  return a;
 }, []);

 console.log(new_array);

Upvotes: 1

diavolic
diavolic

Reputation: 722

for (i=0; i<arr.length-1; i++)
   new_arr[] = parseInt(arr[i+1])-parseInt(arr[i])

Upvotes: 0

Ngoan Tran
Ngoan Tran

Reputation: 1527

Try with below solution:

var arr = ["003448", "003609", "003729", "003800", "004178", "004362", "004410"];
var new_arr =  [];

for (var i=1; i<arr.length; i++){
  new_arr.push(arr[i]-arr[i-1]);
}

console.log(new_arr);

Upvotes: 0

Related Questions