what is the wrong with this javascript function? - javascript

I want to know what is wrong with this function that takes array and summation it's elements
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = 0;
var arraySum = function () {
for (var i = 0 ; i<= arr.length ; i++) {
sum += arr[i];
}
console.log(sum);
};
arraySum(arr);

You are trying to access an element outside of the array, this returns undefined.
for (var i = 0 ; i<= arr.length ; i++) {
// ^ the equal sign
replace it with
for (var i = 0 ; i< arr.length ; i++) {
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = 0;
var arraySum = function () {
for (var i = 0; i< arr.length; i++) {
sum += arr[i];
}
};
arraySum(arr);
document.write(sum);

The problem is there with your for loop's condition. Use < when you are checking against the length,
for (var i = 0 ; i < arr.length ; i++) {
//------------------^ replaced the <= with <
Your loop will iterate additionally one time, at that time the value will be undefined.
So sum + undefined = NaN.
If you want to use <= for sure then subtract 1 from the length and use it.
for (var i = 0 ; i <= arr.length-1 ; i++) {
//------------------------------^ decrement the length by 1
Or you can do the entire process with Array.prototype.reduce
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = arr.reduce((a, b) => { return a + b }, 0);

Also you can use Array.prototype.forEach function
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = 0;
arr.forEach(function(element) {
sum += element;
});
console.log(sum);

Related

How to reverse the array with the function reverseArray

You are given an array with N length. Please develop the function reverseArray to reverse the array
E.g.
Input: [1, 2, 3, 4, 5]
Output:
5
4
3
2
1
My attempt is as follows:
function printArray (inputArray){
for(let i = 0; i < inputArray.length; i++){
console.log(inputArray[i]);
}
}
function reverseArray (inputArray){
for (var i = inputArray.length - 1; i >= 0; i--){
inputArray.push(inputArray[i]);
}
printArray(inputArray);
}
reverseArray([1, 2, 3, 4, 5]);
But it turns out to be as follows:
1 2 3 4 5 5 4 3 2 1
Can anyone teach me how to solve, i have been struggling with this question for 2 days
Check
this link
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var a = [3,5,7,8]
var b = reverseArr(a);
You can use reverse() and join()
var arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr.join(' '));
Use for loop:
function printArray (inputArray){
for(let i = 0; i < inputArray.length; i++){
console.log(inputArray[i]);
}
}
function reverseArray (inputArray){
var results = [];
for (var i = inputArray.length - 1; i >= 0; i--){
results.push(inputArray[i]);
}
printArray(results);
}
reverseArray([1, 2, 3, 4, 5]);
User array's reverse method:
function printArray (inputArray){
for(let i = 0; i < inputArray.length; i++){
console.log(inputArray[i]);
}
}
function reverseArray (inputArray){
var results = [];
results = inputArray.reverse();
printArray(results);
}
reverseArray([1, 2, 3, 4, 5]);
A bit change on your base code. It could be simpler, but I think what you need is a inplace reverse.
function printArray(inputArray) {
for (let i = 0; i < inputArray.length; i++) {
console.log(inputArray[i]);
}
}
function reverseArray(inputArray) {
const tempArr = inputArray.slice();
inputArray.splice(0, inputArray.length);
for (var i = tempArr.length - 1; i >= 0; i--) {
inputArray.push(tempArr[i]);
}
printArray(inputArray);
}
reverseArray([1, 2, 3, 4, 5]);
there are many ways to do this. and there is a reverse method for array too.
function reverseArray(inputArray) {
let start = 0;
let end = inputArray.length -1;
while (start < end) {
const tmp = inputArray[start];
inputArray[start] = inputArray[end];
inputArray[end] = tmp;
start++;
end--;
}
}
arr = [1, 2, 3, 4, 5];
reverseArray(arr);
console.log(arr);
thats very simple you can use javascript method "reversed()"
or you can use this function
function reverse(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var arr = [3,5,7,8]
var b = reverse(arr)
console.log(b)
The easiest method for reserve array is using Array.reverse;
But if you want do it by yourself,you can do it like this:
function reserveArray (input){
for (let i =0;i<input.length;i++){
input.unshift(input.pop())
}
}
It's just an idea, and i do not test if it run as expected.
You could iterate through half the array and swap [i] and [inputArray.length-1-i].
function reverseArray(a) {
for(let i = 0; i < Math.floor(a.length / 2); i++) {
[a[i], a[a.length - 1 - i]] = [a[a.length - 1 - i], a[i]];
}
}
If the output is really a string (opposed to an array) just print the elements start from the end:
function reverseArray(a) {
for(let i = a.length - 1; i >= 0; i--) {
process.stdout.write(a[i].toString() + (i ? " " : ""));
}
}

Getting values higher than average in Array - JS

I'm trying to get all the numbers that are higher than the average of a given Array.
(this goes into an HTML page so it's with document.write
this is what I wrote:
sumAndBigger(arrayMaker());
function sumAndBigger(array) {
for (i = 0; i < array.length; i++) {
sum += array;
}
var equalAndBigger = []
var avg = sum / array.length;
for (i = 0; i < array.length; i++) {
if (array[i] > avg) {
equalAndBigger.push(array[i])
}
}
document.write('The numbers are: ' + equalAndBigger)
}
function arrayMaker() {
var array = [];
for (i = 0; i < 5; i++) {
var entrie = +prompt('Enter a number: ');
array.push(entrie)
}
return array;
}
This doesn't seem to work.. what am I doing wrong here?
Thanks in advance!
Ok so here I am giving you a one-liner code to get all the elements from the array that are "strictly greater than" the average value
let array = [1, 2, 3, 4, 5]
let allNums = array.filter(v => v > array.reduce((x, y) => x + y) / array.length);
Explanation
array.reduce((x, y) => x + y) → sum of all elements in the array
array.reduce((x, y) => x + y) / array.length → getting the average
Output
[4, 5]
MORE DETAILED CODE
function getAverage(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
function getGreaterThanAverage(arr) {
let avg = getAverage(arr);
let numbers = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > avg) {
numbers.push(arr[i]);
}
}
return numbers;
}

Write a sum() function that takes an array of numbers

Can someone please explain to me what I am doing wrong here...
This code is from eloquent javascript and it works fine
function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}
And this is what I wrote for the exercise but returns NaN..
function sum(numArray) {
let add = 0;
for (let a = 0; a <= numArray.length; a++) {
let addIndex = numArray[a];
add += addIndex;
}
return add;
}
Your for loop goes out of array indexes. You have to use:
a < numArray.length
Instead of:
a <= numArray.length
You simply add undefined to add, because you run the index count to long.
for (let a = 0; a <= numArray.length; a++) {
// ^ wrong, takes last index + 1
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4]));
The issue is because of this a <= numArray.length. Change it to a < numArray.length. This case a[5] that is the 6th element or the element at 5th index is undefined as the array starts from 0 index. So it will add an undefined with previously added number and hence it will be NaN
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4, 5]))
You're getting an out-of-bounds error. In your for loop, you can change it to:
for (let a = 0; a < numArray.length; a++) {
OR
for (let a = 0; a <= numArray.length - 1; a++) {
The latter works too, but is harder to read.
You can also write a function that has two parameters, an array and a callback function that adds the values of the array like
function forEach(array, arrayAdder){
for (var i = 0; i < array.length; i ++)
arrayAdder(array[i]) ;
}
We can now initialize both the array and the sum like
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], sum = 0;
After that we pass it into the function like this
forEach(array, function(number){
sum += number ;
});
Then print the answer
console.log(sum);

How to programmatically create 3D array that increments to a defined number, resets to zero, and increments again?

Starting with this initial 2D array:
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
I need to create this 3D array programmatically:
var fullArray = [
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]],
[[6,7],[3,4],[1,2],[5,6],[2,3],[6,7]],
[[0,1],[4,5],[2,3],[6,7],[3,4],[0,1]],
[[1,2],[5,6],[3,4],[0,1],[4,5],[1,2]],
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]]
];
See the pattern?
On each pair, the [0] position should increment to 6 (from any starting number <= 6) and then reset to 0 and then continue incrementing. Similarly, the [1] position should increment to 7 (from any starting number <= 7) and then reset to 1 and then continue incrementing.
In this example, there are 10 2D arrays contained in the fullArray. However, I need this number to be a variable. Something like this:
var numberOf2DArraysInFullArray = 12;
Furthermore, the initial array should be flexible so that initialArray values can be rearranged like this (but with the same iteration follow-through rules stated above):
var initialArray = [[6,7],[2,3],[5,6],[4,5],[1,2],[6,7]];
Any thoughts on how to programmatically create this structure?
Stumped on how to gracefully pull this off.
Feedback greatly appreciated!
Here's a solution, I've separated the methods, and I made it so if instead of pairs it's an N size array and you want the [2] to increase up to 8 and reset to 2, if that's not needed you can simplify the of the loop for(var j = 0; j < innerArray.length; j++)
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var create3DArray = function(array, size){
var newArray = [initialArray];
for(var i = 0; i < size; i++)
{
newArray.push(getNextArrayRow(newArray[i]));
}
return newArray;
}
var getNextArrayRow = function(array){
var nextRow = [];
for(var i = 0; i < array.length; i++)
{
var innerArray = array[i];
var nextElement = [];
for(var j = 0; j < innerArray.length; j++)
{
var value = (innerArray[j] + 1) % (7 + j);
value = value === 0 ? j : value;
nextElement.push(value);
}
nextRow.push(nextElement);
}
return nextRow;
}
console.log(create3DArray(initialArray,3));
Note, the results from running the snippet are a bit difficult to read...
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var numOfArrays = 10;
// get a range array [0, 1, 2, ...]
var range = [];
for (var i = 0; i < numOfArrays; i++) {
range.push(i);
}
var result = range.reduce(function(prev, index) {
if (index == 0) {
return prev;
}
prev.push(transformArray(prev[index - 1]));
return prev;
}, [initialArray])
console.log(result);
function transformArray(arr) {
return arr.map(transformSubArray)
}
function transformSubArray(arr) {
return arr.map(function(val) {
return val == 7 ? 0 : val + 1;
})
}
Here's a pretty simple functional-ish implementation

Arrays acting odd

So, I'm working on a javascript application that can solve any size matrix. I'm running into a SUPER weird problem, where my main array only has the value of 0 after a certain point. The input should be a data set, like this
1, 8
2, 10
3, 13
4, 17
5, 22
But I'm having trouble with it. When I run the code, the console.log prints out a pretty derpy array
[[1, 1, 1, 8],
[0, 0, 0, 0],
[0, 0, 0, 0]]
It gets even weirder. If I move the console.log to before I call the rref function, I get the same thing.
Anybody ever seen this before? Anyone know how to fix it? Thanks!
//Matrix object
var matrix = {
startingDataSet: [],
degree: 0,
M: []
}
//splits up user input into a more readable format
function getDataFromString(data) {
var points = data.split("\n");
for (var i=0; i<points.length; i++) {
points[i] = points[i].split(", ");
points[i][0] = parseInt(points[i][0]);
points[i][1] = parseInt(points[i][1]);
}
return points;
}
//finds the degree of the polynomail from the matrix object's data
function setPolynomialDegree(original) {
var data = original;
console.log(original);
//temporary data set to hold numbers in
var tempNumbers = [];
var degree = 1;
//move the original set of Y values into the temporary data set
for (var i = 0; i < data.length; i++) {
tempNumbers.push(data[i][1]);
}
//while the numbers in tempdata are not the same, execute subtraction
while (tempNumbers[0] != tempNumbers[1]) {
var newnums = []
var l = tempNumbers.length;
//find the difference for every set of numbers (0 & 1, 1 & 2, 2 & 3, etc.), and push those into the new data set
for (var i = 0; i < l - 1; i++) {
newnums.push(tempNumbers[i + 1] - tempNumbers[i]);
}
//replace old data set with new one
tempNumbers = newnums;
//increase polynomial degree by one
degree += 1;
}
return degree;
}
//add 2 arrays together
function addrows(r1, r2) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] + r2[i]);
}
return temprow;
}
//multiply array by constant
function multrow(r1, num) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] * num);
}
return temprow;
}
//rref function
function rref(mtrx, deg) {
var temp1 = [];
var temp2 = [];
for (var row = 0; row < mtrx.length; row++) {
for (var j = 0; j < mtrx.length-1; j++) {
temp1 = multrow(mtrx[row], mtrx[j+1][row]);
temp2 = multrow(mtrx[j+1], mtrx[row][row]);
temp1 = multrow(temp1, -1);
mtrx[j+1] = addrows(temp1, temp2);
}
}
return mtrx;
}
//Main function that will solve the matrix
function solveFromDataSet(data) {
data = getDataFromString(data);
for (var i=0; i<data.length; i++) {
matrix['startingDataSet'].push(data[i]);
}
matrix.degree = setPolynomialDegree(matrix.startingDataSet);
matrix.M = [];
for (var i = 0; i < matrix.degree; i++) {
var row = [];
for (var j = matrix.degree; j > 0; j--) {
row.push(Math.pow(data[i][0], j - 1));
}
row.push(data[i][1]);
matrix['M'][i] = row;
}
var var_array = rref(matrix['M']);
console.log(matrix.M);
return matrix.M;
}

Categories

Resources