I\'m trying to square each number in an array and my original code didn\'t work. I looked up another way to do it, but I\'d like to know WHY the original code didn\'t work.<
Best way to Square each number in an array in javascript
Array.prototype.square = function () {
var arr1 = [];
this.map(function (obj) {
arr1.push(obj * obj);
});
return arr1;
}
arr = [1, 6, 7, 9];
console.log(arr.square());
arr1 = [4, 6, 3, 2];
console.log(arr1.square())
function squareDigits(num){
//may the code be with you
var output = [];
var splitNum = num.toString();
for(var i = 0; i < splitNum.length; i++){
output.push(splitNum.charAt(i))
}
function mapOut(){
var arr = output;
return arr.map(function(x){
console.log(Math.pow(x, 2));
})
}
mapOut();
}
squareDigits(9819);
This should work
Math.sqrt
gives you square root not square of a number. Use Math.pow
with second argument of 2
.
Avoid unnecessary loops, use map()
function
let array = [1,2,3,4,5];
function square(a){ // function to find square
return a*a;
}
arrSquare = array.map(square); //array is the array of numbers and arrSquare will be an array of same length with squares of every number
You can make the code shorter like this:
let array = [1,2,3,4,5];
arrSquare = array.map(function (a){return a*a;});
The original code is taking the square root of the value. The second version is multiplying the value with itself (squaring it). These are inverse operations
function map(square,a) {
var result = [];
for(var i=0;i<=a.length-1;i++)
result[i]=square(a[i]);
return result;
}
var square = function(x) {
return x*x;
}
var value=[1,2,3,4];
var final= map(square,value);
console.log(final);
You can also try the above code snippet.