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.
-
1"The next value will be reduced by previous value"Joseph– Joseph2017年03月28日 01:58:05 +00:00Commented Mar 28, 2017 at 1:58
-
yes.. if we have array like this [1, 5, 9, 12] then by following the rule it will become 5-1 = 4, 9-5 = 4, 12-9 = 3 then the new array is [4, 4, 3]fandiahm– fandiahm2017年03月28日 02:00:16 +00:00Commented Mar 28, 2017 at 2:00
3 Answers 3
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);
Sign up to request clarification or add additional context in comments.
1 Comment
nnnnnn
Note that the
parseInt() calls are redundant, because the - operator coerces its arguments to be numbers.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);
answered Mar 28, 2017 at 1:58
Ngoan Tran
1,5571 gold badge13 silver badges17 bronze badges
1 Comment
fandiahm
Thank you very much.. This is great!
for (i=0; i<arr.length-1; i++)
new_arr[] = parseInt(arr[i+1])-parseInt(arr[i])
answered Mar 28, 2017 at 1:59
diavolic
7161 gold badge4 silver badges5 bronze badges
Comments
lang-js