Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I subtract 1 from each number in an array? [duplicate]

If I have

var numberarr = [1, 2, 3, 4, 5];

How would i make it into

var numberarr2 = [0, 1, 2, 3, 4];

by decrementing 1 from each element?

like image 265
W30 Avatar asked Oct 11 '15 01:10

W30


People also ask

How do you subtract numbers in an array?

Find the minimum non-zero element in the array, print it and then subtract this number from all the non-zero elements of the array. If all the elements of the array are < 0, just print 0. Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Can I subtract from array Java?

Java Array Subtract subtractElementwise(int[] a, int[] b) Subtracts the values in the two arrays of integers element-wise.

Can you subtract two arrays in C?

One way you can do this is to pass the result array as a parameter to the subtract() function. You should, of course, make sure that all arrays are of the same size NUM so that there is no memory access errors. Then you can print all the three arrays in your main() .


2 Answers

You can use .map( )

var numberarr2 = numberarr.map( function(value) { 
    return value - 1; 
} );
like image 79
Austin Brunkhorst Avatar answered Oct 05 '22 21:10

Austin Brunkhorst


Try this:

// Create an array to hold our new values
var numberArr2 = [];

// Iterate through each element in the original array
for(var i = 0; i < numberArr1.length; i++) {

    // Decrement the value of the original array and push it to the new one
    numberArr2.push(numberArr1[i] - 1);
}
like image 27
Heman Gandhi Avatar answered Oct 05 '22 19:10

Heman Gandhi