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.
Original code:
function(arr) {
ret= [];
for (var i = 0, len = arr.length; i < len; i++) {
root = Math.sqrt(arr[i]);
ret.push(root);
}
return ret;
}
Working Code:
function(arr) {
ret= [];
for (var i = 0, len = arr.length; i < len; i++) {
ret.push(arr[i] * arr[i]);
}
return ret;
}
Math.sqrt gives you square root not square of a number. Use Math.pow with second argument of 2.
How about that ?
function (arr) {
return arr.map(function (x) {
return Math.pow(x, 2);
});
}
Array.map(func) applies the function to each element of the map and returns the array composed of the new values.
Math.pow(base, exp) raises base to its exp power.
The first sample is taking the square root, not squaring the value. To square you want to use
Math.pow(arr[i],2);
Here is how it can be done, using a simple method called .forEach
var numbers = [1,2,3,4,5,6,7,8];
numbers.forEach(function(element, index, array){
array[index] = element* element;
});
console.log(numbers);
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())
Here is the function write with ES6 Exponentiation (**):
let arr = [1, 6, 7, 9];
let result = arr.map(x => x ** 2);
console.log(result);
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
I hope this answers your question
const numbers = [1,2,3,4,5,6,7,8,9];
for(let squareIt of numbers){
console.log(Math.pow(squareIt, 2));
}
Resolved by kiss-barnabas
Use embedded for , for pretty syntax :
var arr=[1,2,3,4] ;
[for (i of arr) i*i ];
//OUT : > [1,4,9,16]
Declarative Programming :)
let list = [1,2,3,4,5,6,7,8,9,10];
let result = list.map(x => x*x);
console.log(result);
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;});
let arr = [1, 2, 3];
let mapped = arr.map(x => Math.pow(x, 2));
console.log(mapped);
This should work.
let kiss=[3,4,5,6];
let arra=[];
for(o in kiss){
arra.push(kiss[o]*kiss[o])
}
console.log(kiss=arra)
using array square root of the first number is equal to the cube root of the second number
function SquareAndCube(arr) {
let newarr = [];
for(i=0 ; i<arr.length; i++) {
if(Math.sqrt(arr[0])/2 === Math.cbrt(arr[1])/2 ) {
return true;
} else return false;
}
}
console.log(SquareAndCube([36, 215]))
This should work with the .map() method:
const number = [2, 6, 6, 2, 8, 10];
const squareNumber = number.map(num => num*num);
console.log(squareNumber);
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
This will work
const marr = [1,2,3,4,5,6,7,8,9,10];
console.log(marr.map((x) => Math.pow(x, 2)));
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.
Related
I have an array like so [1,9,9,9,9,9]. I want to increment this array by one and return [2,0,0,0,0,0]. Here's the catch - you can't join() or concat(). You cannot change the array in any way other than adding to it. However, you can reverse it but I'm not sure how much that would help
Also, here are a few other examples;
[1,8,9] => [1,9,0];
[1,2,3,9,1] => [1,2,3,9,2];
[5,7,9,9] => [5,8,0,0];
The result can only return an array with single digits.
Basically, pretend that the array is a single number and you're adding 1 to it. Again, no joining, splitting, turning into a string.. etc.
Ideally, I would like a classic loop solution or possibly a recursion solution. Thank you!
here is my repl.it https://repl.it/#CharChar5/Code-Challenge
Thank you in advance for your help and I'm terribly sorry if my questions title is too long and confusing. I'm certainly working on formatting better questions and building a stronger rep on SO.
https://repl.it/#CharChar5/Code-Challenge
Currently this is my code:
jjChallenge=(j)=>{
const len = j.length;
const newArray = [];
for(var i = 0; i<j.length; i++){
if (j[i] == 9) {
if(j[i-1] == 9) {
n = 0;
} else {
newArray[i-1] = newArray[i-1] + 1;
n = 0;
}
newArray.push(n);
} else {
newArray.push(j[i]);
}
}
console.log(newArray)
}
jjChallenge([2,9,9,9]) //works and returns [3,0,0,0]
//[2,9,8,9] doesnt work and returns [3,0,9,0]
Reverse it and increment with carry and then reverse it back
Something like
eg
function incrementIntArray(arr) {
var reverseArray = arr.reverse();
var newReverseArray = [];
var carry = false;
for (var i = 0; i < arr.length; i++) {
var curNum = reverseArray[i];
if (i == 0 || carry) curNum++;
if (curNum > 9) {
carry = true;
curNum = 0;
} else {
carry = false;
}
newReverseArray[i] = curNum;
}
return newReverseArray.reverse();
}
var arr1 = [1, 8, 9];
var arr2 = [1, 2, 3, 9, 1];
var arr3 = [5, 7, 9, 9];
console.log(incrementIntArray(arr1)); //outputs [1,9,0]
console.log(incrementIntArray(arr2)); //outputs [1,2,3,9,2]
console.log(incrementIntArray(arr3)); //outputs [5,8,0,0]
Your code was trying to carry, but it's difficult to carry when coming from the top down, hence the reverse and then its easier to carry from bottom up
Here ya go:
jjChallenge=(arr)=>{
newArray=arr.map((element) => {
return element==9?0:element+1
})
return newArray
}
jjChallenge([2,9,9,9])
Just sum the digits up and then plus one. After that, split it.
Simple and Clean that complies with
you can't join() or concat(). You cannot change the array in any way other than adding to it.
addOne = (data) => {
let sum = 0, digit = data.length - 1
data.forEach(n => sum += n * (10 ** digit--))
return (sum + 1).toString().split("")
}
console.log(addOne([1,8,9]))
console.log(addOne([1,2,3,9,1]))
console.log(addOne([5,7,9,9]))
Please help me with this code; I am trying to compare arguments with an array elements and return when it matches, I don't know what is wrong with this code, it returns 1 rather than an array , thanks.
const removeFromArray = function() {
var delArgs = [] ;
//convert the arguments to an array called 'args'.
var args = Array.from(arguments);
var Arr = args[0];
//using foreach() and forloop to compare arguments with Arr elements.
Arr.forEach(function(x){
for (var j=1 ; j < args.length ; j++){
if(x == args[j]){
delArgs = delArgs.push(x);
}
}
});
return delArgs;
}
removeFromArray([1,2,3,4,5,6] , 5);
1
delArgs = delArgs.push(x);
You're overwriting delArgs with the return value from push, which is the new length of the array.
Don't do that.
since the question is already answered, you could use this for shorter code
const removeFromArray = (array, ...args) => {
return args.filter( arg => array.includes(arg) )
}
console.log(removeFromArray([1, 2, 3, 4, 5, 6], 5,6));
I am trying to write the logic to delete element by passing indexArr(that contains indexes to delete) to a method:
var a = [0,1,2,3,4,5];
Array.prototype.removeElem = function(indexArr){
this.filter(function(value,index,arr){
return indexArr.indexOf(index)>-1 ? arr[index] = undefined:false
}
});
}
a.removeElem([2,3]); //passing indexes in form of array
console.log(a.join('').split('')); //removing undefined values
As you can see, I am removing undefined values after the execution of removeElem() method, but I want to do that in the method itself.
To modify an original array, you can use while() loop from last to first index combined with splice() method:
var a = [0,1,2,3,4,5];
Array.prototype.removeElem = function(indexArr){
var length = this.length;
while(length--) {
if(indexArr.indexOf(length) > -1) {
this.splice(length, 1);
}
}
}
console.log(a.removeElem([0,1]));
console.log(a);
No need to use Array.filter(). Try something like this :
let a = [0, 1, 2, 3, 4, 5];
Array.prototype.removeElem = function(indexArr) {
let removedElem = 0;
for (let i = 0; i < indexArr.length; i++) {
this.splice(indexArr[i] - removedElem, 1)
removedElem += 1;
};
return this;
}
console.log(a.removeElem([2, 3]));
simple :)
EDIT:
var a = [0,1,2,3,4,5];
Array.prototype.removeElem = function(indexArr){
indexArr.sort();
i=indexArr.length;
while(i--)
{
a.splice(indexArr[i],1);
}
}
a.removeElem([2,3]); //passing indexes in form of array
console.log(a);
you can make use of reduce for this.
check the following code snippet
var a = [0, 1, 2, 3, 4, 5];
Array.prototype.removeElem = function(indexArr) {
return this.reduce((result, key, index) => {
if (indexArr.indexOf(index) === -1) {
result.push(key)
}
return result
}, [])
}
var result = a.removeElem([2, 3]); //passing indexes in form of array
console.log(result.join('').split(''));
Hope it helps
use splice method to add and remove element from array
If I have an array like [1,2,3,4], and I want to duplicate and reverse it, how do I get it to return [1,2,3,4,4,3,2,1]?
Array.prototype.duplicateAndReverse = function() {
const initial = this;
const reversed = initial.reverse();
return initial.concat(reversed);
}
What am i doing wrong here? It returns [4,3,2,1,4,3,2,1]
Try this:
Array.prototype.duplicateAndReverse = function() {
const initial = this;
const reversed = initial.slice().reverse();
return initial.concat(reversed);
}
var myArray = [1,2,3,4];
alert(myArray.duplicateAndReverse());
Your code is reversing initial as well as setting reversed to the result, so you have two identical (reversed) arrays. Instead, use .slice() to duplicate the initial array, and reverse that instead.
var arr = [1,2,3,4];
for(var len = arr.length; len; len--)
arr.push(arr[len - 1]);
console.log(arr);
I don't recommend you mess with Array.prototype but here is what you want:
Array.prototype.duplicateAndReverse = function() {
let res = this.slice(); // create another copy so the original array will stay intact
for(var len = res.length; len; len--)
res.push(res[len - 1]);
return res;
}
let arr = [1, 2, 3, 4];
console.log(arr.duplicateAndReverse());
The problem was that you tried to reverse the initial array in place.Use the following optimized solution:
Array.prototype.duplicateAndReverse = function() {
return this.concat(this.slice().reverse());
}
console.log([1,2,3,4].duplicateAndReverse());
To retain the original array and create its reversed copy use Array.prototype.slice() function combined with Array.prototype.reverse() function
This is your problem because reverse() also reverse the original array
arr
var arr = [1,2,3,4]
var dup = arr.reverse()
console.log(arr) // => [4, 3, 2, 1]
console.log(dup) // => [4, 3, 2, 1]
You need to clone the original array first
var dup = arr.slice().reverse()
And then you can concat the 2 arrays to get the result. Happy coding!
Oriental solution, hihi.
var arr = [1,2,3,4];
var newArr = [];
arr.forEach((_,i) => newArr.unshift(arr[arr.length-i-1]) && newArr.push(arr[arr.length-i-1]))
console.log(newArr);
I have 2 array:
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];
Want to get 1 merged array with the sum of corresponding keys;
var array1 = [[1,10],[2,10],[3,10],[4,10],[5,50],[6,50],[7,10],[8,10],[9,10]];
Both arrays have unique keys, but the corresponding keys needs to be summed.
I tried loops, concat, etc but can't get the result i need.
anybody done this before?
You can use .reduce() to pass along an object that tracks the found sets, and does the addition.
DEMO: http://jsfiddle.net/aUXLV/
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];
var result =
array1.concat(array2)
.reduce(function(ob, ar) {
if (!(ar[0] in ob.nums)) {
ob.nums[ar[0]] = ar
ob.result.push(ar)
} else
ob.nums[ar[0]][1] += ar[1]
return ob
}, {nums:{}, result:[]}).result
If you need the result to be sorted, then add this to the end:
.sort(function(a,b) {
return a[0] - b[0];
})
This is one way to do it:
var sums = {}; // will keep a map of number => sum
// for each input array (insert as many as you like)
[array1, array2].forEach(function(array) {
//for each pair in that array
array.forEach(function(pair) {
// increase the appropriate sum
sums[pair[0]] = pair[1] + (sums[pair[0]] || 0);
});
});
// now transform the object sums back into an array of pairs
var results = [];
for(var key in sums) {
results.push([key, sums[key]]);
}
See it in action.
a short routine can be coded using [].map()
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];
array1=array2.concat(array1).map(function(a){
var v=this[a[0]]=this[a[0]]||[a[0]];
v[1]=(v[1]||0)+a[1];
return this;
},[])[0].slice(1);
alert(JSON.stringify(array1));
//shows: [[1,10],[2,10],[3,10],[4,10],[5,50],[6,50],[7,10],[8,10],[9,10]]
i like how it's just 3 line of code, doesn't need any internal function calls like push() or sort() or even an if() statement.
Try this:
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];
var res = [];
someReasonableName(array1, res);
someReasonableName(array2, res);
function someReasonableName(arr, res) {
var arrLen = arr.length
, i = 0
;
for(i; i < arrLen; i++) {
var ar = arr[i]
, index = ar[0]
, value = ar[1]
;
if(!res[index]) {
res[index] = [index, 0];
}
res[index][1] += value;
}
}
console.log(JSON.stringify(res, null, 2));
So, the result may have holes. Just like 0th index. Use the below function if you want to ensure there are no holes.
function compact(arr) {
var i = 0
, arrLen = arr.length
, res = []
;
for(i; i < arrLen; i++) {
var v = arr[i]
;
if(v) {
res[res.length] = v;
}
}
return res;
}
So, you can do:
var holesRemoved = compact(res);
And finally if you don't want the 0th elem of res. Do res.shift();
Disclaimer: I am not good with giving reasonable names.
The simple solution is like this.
function sumArrays(...arrays) {
const n = arrays.reduce((max, xs) => Math.max(max, xs.length), 0);
const result = Array.from({ length: n });
return result.map((_, i) => arrays.map(xs => xs[i] || 0).reduce((sum, x) => sum + x, 0));
}
console.log(...sumArrays([0, 1, 2], [1, 2, 3, 4], [1, 2])); // 2 5 5 4