1

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.

2
  • 1
    "The next value will be reduced by previous value" Commented 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] Commented Mar 28, 2017 at 2:00

3 Answers 3

1

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

Note that the parseInt() calls are redundant, because the - operator coerces its arguments to be numbers.
0

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);

1 Comment

Thank you very much.. This is great!
0
for (i=0; i<arr.length-1; i++)
   new_arr[] = parseInt(arr[i+1])-parseInt(arr[i])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.