use math abc on all array items

Viewed 79

array => math.abc


my array is :

var arr = [9 , -2 , -10 ,2 ,-21]

and i want use math.abc to get 9 ,2 ,10 ,2 21 in new array. how can i do this ? :p


this is my code :

var n = 5;
var inputs = [1, -2, -8, 4, 5];
for (var i = 0 ; i === n ; i++){
  Math.abs(inputs[i]);
  console.log(inputs[i]);
}

but i don't know why it don't work :(

bruh why its hard to send questions ? :\

3 Answers

It's Math.abs, not math.abc.

Map the array through Math.abs and log it.

var arr = [9 , -2 , -10 ,2 ,-21];
console.log(
  arr.map(Math.abs)
);

Primitives are immutable. Just calling Math.abs on a value doesn't do anything to the value - you'd need to assign the result to something to see a change.

Your for loop condition is wrong too, you never defined n, and the condition should be truthy while the loop is running: i < inputs.length, not i === n.

First of all, you do not need to specify array length in a separate variable. More flexible way is to use inputs.length.

Secondly, the condition in your for loop is wrong - it should be i < n.

Thirdly, just calling Math.abs, does nothing. If you want to mutate your original array then you can update your code as following:

var inputs = [1, -2, -8, 4, 5];
for (var i = 0; i < inputs.length ; i++){
  inputs[i] = Math.abs(inputs[i]);
}
console.log(inputs);

If you want to create a new array with absolute numbers, use Array.prototype.map, like this:

var inputs = [1, -2, -8, 4, 5];
var absoluteValues = inputs.map(Math.abs);
console.log(absoluteValues);

If it is not fully clear to you, you can use more descriptive code:

var absoluteValues = inputs.map(function(number) {
    return Math.abs(number);
});

Actually you are going well but you should focus at two point in your code.

First you have a loop to get all the values in array right. So you should begin at i=0 and get the last value at index of n-1.

For loops has 3 parts. First the definition of your iterate value, second is the condition and the third one is the operation that you want to do at end of the every step in the loop. They seperated with ';'. In your condition part you just said Keep going while my i value is equal to n(the length of the array) .

for(i=0;i===n;i++)

but you shouldn't do that. Cause it will work if only your i equals to n, so will pass it at first iterate cause i=0 and n = 5 so not equal.

You want to take all the values so you want to get the values at 0 to n-1 index so,if your i is less than n go ahead, but you get the all values and your i is equal or bigger than N then stop.

So

for(i=0;i<n;i++)

And the second point is, you are not changing the value with Math.abs you are just print it. You should assign the Math.abs value to the old values index. So

inputs[i] = Math.abs(inputs[i])

And Finally

var n = 5;
var inputs = [1, -2, -8, 4, 5];
for (var i = 0 ; i < n ; i++){
   inputs[i]=Math.abs(inputs[i]);      
}
console.log(inputs)

Related