function that squares the values in an array - javascript

i've been instructed to create a function that takes values from an array and squares each value, and logging the numbers to the console. i've attempted two methods, neither of which work so far:
first attempt:
var numbers = [2, 7, 13, 24];
function squareAll(numbers) {
var newArray = [];
for(i = 0; i < numbers.length; i++) {
numbers = newArray.push(Math.pow(numbers[i], 2))
return newArray;
}
console.log(squareAll(numbers));
}
second attempt:
var numbers = [2, 7, 9, 25];
var newArray = [];
var squareAll = function(numbers) {
for(var i = 0; i < numbers.length; i++){
newArray = [];
newArray.push(squareAll[i] * squareAll[i])
};
return newArray;
};
console.log(squareAll(newArray));
when i try both codes in the javascript console, both return undefined and won't give me a specific error so i'm unsure what's wrong here. any explanation would be appreciated!

In your first attempt you are assigning a push method into a variable, which is a bad practice. Secondly, you are returning the function just right after the first cycle of the loop, so you are stopping the loop before going through all the elements of the array.
And in the second attempt, you are basically clearing the array after each cycle of the loop, because of the newArray = []; inside the loop. So with every cycle, you are dropping an element inside the newArray and then you are telling the loop to clear the newArray. The loop will become infinite, because the length of the newArray will never reach the numbers.length.
var numbers = [2, 7, 13, 24];
var newArray = [];
console.log(numbers.map(v => Math.pow(v, 2)));
Or:
var numbers = [2, 7, 13, 24];
var newArray = [];
for (var i = 0; i < numbers.length; i++) {
newArray.push(Math.pow(numbers[i], 2));
}
console.log(newArray);

Why not just use map
var result = [1,2,3,4,5].map(function(val){
return Math.pow(val,2);
});
console.log(result); // [1, 4, 9, 16, 25]

Use array.map() to set a callback function to be executed for each element in the array:
var arr1 = [1,2,3,4];
function squareIt(arr) {
return arr.map(function (x) {
return Math.pow(x, 2);
});
}
alert(squareIt(arr1));

Related

Make array numbers negative

I'm trying to return all array numbers as negative numbers (* -1);
I'm stuck. Please help!
function makeListNegative (array){
for(i=0; i <array.length; i++);
return i * -1;
}
var negativeList = makeListNegative([7, 2, 3, 4]);
console.log(negativeList);
This function only returns that last number in the array as -4. I would like ALL list numbers to be displayed.
You need to map the values to negative values.
function makeListNegative(array) {
return array.map(x => x * -1);
}
var negativeList = makeListNegative([7, 2, 3, 4]);
console.log(negativeList);
function makeListNegative (array) {
for (i = 0; i < array.length; i++); // 1
return i * -1; // 2
}
Your for statement iterates (in the right range with the right interval), but with the semicolon at the end of the line, it perform no operation.
Then you return the negative value of i, which is the length of the array, not a value of the array or an array with all negative values.
If you like to get you traditional approach, you could push the value in every iteration to a new array and return the new array after the iteration.
function makeListNegative(array) {
var i, l,
temp = [];
for (i = 0, l = array.length; i < l; i++) {
temp.push(-array[i]);
}
return temp;
}
var negativeList = makeListNegative([7, 2, 3, 4]);
console.log(negativeList);
You could map the negative values with Array#map.
function makeListNegative(array) {
return array.map(v => -v);
}
var negativeList = makeListNegative([7, 2, 3, 4]);
console.log(negativeList);
Your code
returned every iteration
had a semicolon in the wrong place
made the index negative instead of the array item
It could have been fixed like this
function makeListNegative(array) {
for (var i = 0; i < array.length; i++) { // make i local
array[i] *= -1; // negate the array item
}
return array; // return the manipulated array
}
var negativeList = makeListNegative([7, 2, 3, 4]);
console.log(negativeList);
Alternatively use Array.map - here in standard JS - the fat arrow => is ES6+ and does not work in IE
var negativeList = [7, 2, 3, 4].map(function(num) { return -num })
console.log(negativeList);
You can impress your senior devs by using ES6 syntax:
const makeListNegative = array => array.map(num => -num)
const negativeList = makeListNegative([7, 2, 3, 4]);
console.log(negativeList);
And if you don't want to create a function:
const negativeList = [7, 2, 3, 4].map(num => -num);
console.log(negativeList);
If you are using Babel or Typescript in your project, you don't need to worry about IE support because your code will be transpiled to ES5 and will be supported on all browsers.
This will not work as you are returning from your for loop. Try using
Array.map()
You can use map to return negative values
var negativeList= [7, 2, 3, 4].map(function(value){
return -v;
})
Since everyone solved the problem using map, here is how to solve using [forEach][1],
var makeNeg = function(arr){
arr.forEach(function(value, index){
arr[index] = arr[index]*-1;
});
return arr;
}
console.log(makeNeg([7, 2, 3, 4]))

Finding addenth on array - JS

I created a function that will find pairs to add the two numbers that will be equal to the sum.
function findingSum(arr, sum){
var firstElement = [];
var difference = [];
var final = [];
var convertArr = arr.map(function(item){
return parseInt(item, 10);
});
for(var i = 0; i < convertArr.length; i++){
difference.push(sum - convertArr[i]); // subtracted sum from each convertArr item
if(difference[i] + convertArr[i] === sum){ // check if convertArr item was added to difference item === sum
firstElement.push(convertArr[i]); // if so add the convertArritem to the result array
}
if(firstElement[i] + convertArr[i] == sum){
final.push(firstElement[i], convertArr[i]);
}
}
return final;
}
var addNumbers = findingSum([3, 34, 4, 12, 5, 2], 9);
console.log(addNumbers); // --> [4, 5]
So what I did is that I try to get the difference of convertArr[i] and the sum and put them in a difference variable. Then I tried to see if adding difference[i] from the original array will give me the sum. If so I'll add them on firstElement array and try to add each value to the original array and finally push them along with it's addenth if the sum was attain. So when you add this two you'll get the sum.
For some reason my logic doesn't work and it does'nt push things on both firstElement and final array. Can anyone help me with this?>
You could use a hash table for visited values.
var findingSum = function (array, s) {
var a, i,
hash = Object.create(null);
for (i = 0; i < array.length; i++) {
a = array[i];
if (hash[s - a]) {
return [s - a, a];
}
if (!hash[a]) {
hash[a] = true;
}
}
};
console.log(findingSum([3, 34, 4, 12, 5, 2], 9)); // [4, 5]

Why cannot I push new elements into new array?

function findMin(array) {
return Math.min.apply(Math, array);
}
function rearrange(matrix) {
let min = 0;
let newMatrix = [];
for (let i = 0; i < matrix.length; i++) {
let min = findMin(matrix[i]);
newMatrix[i].push(min);
}
return newMatrix;
}
Example input:
let matrix = [[2,7,1],
[0,2,0],
[1,3,1]]
rearrange(matrix);
Log:
Uncaught TypeError: Cannot read property 'push' of undefined
at reArrange (test.js:11)
at test.js:23
I'm trying to have the nested arrays sorted in an increasing order. If I didn't get it wrong, it doesn't happen because newMatrix[i] is not defined. But can't JS just create it and push the element? Do we need an extra step prior to doing this? Could you please suggest me another way, if this method won't work?
That's because you don't initialize the second dimension in your output Array. In JavaScript, if you haven't explicitly assigned to a certain element of an array, it evaluates to undefined, which obviously is neither an Array, nor an array like object and does not have a push() method.
The quickest solution to your problem should be declaring the inner arrays as well.
let newMatrix = [[], [], []];
A better, generic way would be to append an empty array to newMatrix every time you encounter a row that does not exist.
I also suspect that you algorithm is incorrect. Could you specify what exactly you intend to achieve by 'rearranging' the array? Because all your current code does is populate newMatrix with the minimum of each row. You're going to end up with [[1], [0], [1]] with the current fix. Is that intentional? Check your logic.
EDIT: Apparently, you're trying to rearrange the maxtix in such a way that the result contains each row in sorted order. Here's how to do that:
function rearrange(matrix) {
let min = 0;
let newMatrix = [];
for (let i = 0; i < matrix.length; i++) {
let sortedRow = matrix[i].sort((a, b) => a > b)
newMatrix.push(sortedRow);
}
return newMatrix;
}
console.log(rearrange([
[7, 6, 8],
[1, 9, 9],
[8, 5, 1]
]))
You need to make shure that matrix[i] is an array:
(newMatrix[i] || (newMatrix[i] = [])).push(min);
Or you set it to an array directly:
newMatrix[i] = [min];
You need to assign a new array before using Array#push
newMatrix[i] = [];
function findMin(array) {
return Math.min.apply(Math, array);
}
function rearrange(matrix) {
let min = 0;
let newMatrix = [];
for (let i = 0; i < matrix.length; i++) {
let min = findMin(matrix[i]);
newMatrix.push(min);
}
return newMatrix;
}
let matrix = [[2, 7, 1], [0, 2, 0], [1, 3, 1]];
console.log(rearrange(matrix));
.as-console-wrapper { max-height: 100% !important; top: 0; }
As an alternative solution, you could just map the result of findMin.
function findMin(array) {
return Math.min.apply(Math, array);
}
function rearrange(matrix) {
return matrix.map(findMin);
}
let matrix = [[2, 7, 1], [0, 2, 0], [1, 3, 1]];
console.log(rearrange(matrix));
Your code is not working because you miss to initialize the array before to push the min.
In your case you have newMatrix which is an empty array.
But you expect than that the array should have arrays inside:
So before this line:
newMatrix[i].push(min);
You could do:
newMatrix[i] = [];
But in this way what you are going to achieve is a new array with arrays, and each array inside has just the min of the input arrays.
If you want a new array ordered inside, you could do that in this way:
var result = [[5,3,1], [4,5,1]].reduce(function(a, b) {
a.push(b.sort());
return a;
}, []);
console.log(result);

Better way to turn a one-dimensional array into multi-dimensional array by required group size in JS

I am rather new to JS and I was working on a problem that asked to split an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.
I got the problem to work right for all test cases but it suggested using the array `push()` method. I tried it multiple times and couldn't ever get it to work right. I think I was getting messed up with arrays being by reference. I eventually declared a new Array for each element. I went with a more classic deep copy each element at a time. I Didn't go back and try the `push()` method again. There has to be a more efficient way to do this. I want to write good code. Would love to see better versions please.
Thanks!
function chunk(arr, size) {
var group = 0;
var counter = 0;
var even = false;
var odd = false;
if (arr.length % size === 0) {
group = arr.length / size;
even = true;
} else {
group = Math.ceil(arr.length / size);
odd = true;
}
var newArr = new Array(group);
for (var i = 0; i < group; i++) {
newArr[i] = new Array(size);
}
for (i = 0; i < group; i++) {
for (var j = 0; j < size && counter < arr.length; j++) {
newArr[i][j] = arr[counter++];
}
}
return newArr;
}
chunk(['a', 'b', 'c', 'd'], 2);
Using Array.prototype.slice, the function can be written in a shorter way:
function chunk(array, size) {
var result = []
for (var i=0;i<array.length;i+=size)
result.push( array.slice(i,i+size) )
return result
}
You can try the slice method from the Array object. Here's an idea on how to use it.
var arr = [1, 2, 3, 4, 5, 6];
var newArr = [];
newArr.push(arr.slice(0, arr.length / 2));
newArr.push(arr.length / 2, arr.length);
This is just an shallow implementation but you can use the same concept inside a better written function.
Here's an example function:
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
function toChunks(arr, size) {
var i = 0,
chunks = [];
for (; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size););
}
return chunks;
}
toChunks(arr, 2);

How to 'double' numbers in an array, and save it in a new array

This is a 2 step problem:
1.) I am trying to 'double' the contents of one array (original Array), save it in a new array (Doubled Array).
2.) Then assign those two arrays to an Object with 2 attributes.
New Object
Orginal Numbers
Doubled Numbers
This is what I have so far, what am I doing wrong?
var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];
function doubled(arr){
for (var i = 0; i < arr.length; i ++){
var dub = arr[i];
var dubb = dub*2;
doubledNumbers.push(dubb);
}
}
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: doubled(numbers)
};
console.log(collectionNumbers);
The best way to do this in Javascript is using the map function:
var doubledNumbers = numbers.map(n => n*2);
The argument to map is the function that it uses to transform the elements in the first array into the elements in the second array. It is a tremendously useful method.
To answer your original question, the reason you were seeing undefined in collectionNumbers is because you forgot to return doubledNumbers in your function (and functions by default return undefined.
var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];
function doubled(arr){
var doubledNumbers = [];
for (var i = 0; i < arr.length; i ++){
var dub = arr[i];
var dubb = dub*2;
doubledNumbers.push(dubb);
}
return doubledNumbers;
}
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: doubled(numbers)
};
console.log(collectionNumbers);
What's wrong with your current code, is that your doubled function is returning nothing (which means it's returning undefined).
A better function would look like this:
function doubled (arr) {
var doubled = [];
for (var i = 0; i < arr.length; i++) {
doubled.push(arr[i] * 2);
}
return doubled;
}
However, an even better solution would be to just do this:
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: numbers.map(function (n) { return n * 2; })
};
.map is awesome.
Your whole routine can be simplified to
var numbers = [8, 12, 5, 2, 5, 7];
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: numbers.map(function(n) { return n*2; })
};
console.log(collectionNumbers);
using Array.map to create a new array with the doubled numbers
using Array.from, you can double and return new array
let inputArray = [9,8,7,3,2]
let outputArray = Array.from(inputArray, x => x *2) // creates new array
console.log(outputArray)

Categories