javascript infinite loop error multidimensional array sort [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Iam trying to sort a multidimension array and put the highest numbers of each sub-array in an array with a double loop but iam getting an infinite loop error for some reason:
The array to be sorted:
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
The code:
function largestOfFour(arr) {
var temp;
for (var i = 0; i < arr.length; i++) {
var largestNumber = 0;
for (var j = 0; i < arr[i].length; j++) {
if (largestNumber < arr[i][j]) {
largestNumber = arr[i][j];
}
}
temp[i] = largestNumber;
}
return temp;
}

You need two changes, one for the right type of the variable to assign the result, and the check in the for loop with the right variable.
function largestOfFour(arr) {
var temp = []; // necessary
for (var i = 0; i < arr.length; i++) {
var largestNumber = 0;
for (var j = 0; j < arr[i].length; j++) {
// ^^ j instead of i
if (largestNumber < arr[i][j]) {
largestNumber = arr[i][j];
}
}
temp[i] = largestNumber;
}
return temp;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

Related

Using Continue in a While loop in Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
Please help me to find out my mistake(s) in this code.
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
while (i < numbers.length){
if (numbers[i] >70){
continue;
}
console.log(numbers[i])
i++;
}
I want to get output
12
34
23
8
48
But the code shows output:
12
34
23
and the run doesn't stop.
You have an infinite loop, because if numbers[i] > 70 it's not increasing i, so the next loop it's checking that same condition again without an incremented i value. There are multiple ways to fix this, but one option is to output the value when numbers[i] <= 70, and always increment i.
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
while (i < numbers.length){
if (numbers[i] <= 70){
console.log(numbers[i]);
}
i++;
}
Another option would be a different loop:
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
for(i = 0; i < numbers.length; i++) {
if (numbers[i] > 70){
continue;
}
console.log(numbers[i]);
}
Or a simpler way:
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
for(i = 0; i < numbers.length; i++) {
if (numbers[i] <= 70){
console.log(numbers[i]);
}
}
You need to update i value before using continue if you don't the value of i will remain the same which leads to the loop becoming an infinite loop.
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
while (i < numbers.length){
if (numbers[i] >70){
i++;
continue;
}
console.log(numbers[i])
i++;
}
Instead of interrupting the while loop you can re-write your logic as:
if (numbers[i] < 71){
console.log(numbers[i]);
}
so that the default action on each iteration of the loop is simply to increment i and, separately, the console logs a value only if the condition is satisfied.
Working Example:
let numbers = [12, 34, 23, 98, 08, 78, 73, 48];
let i = 0;
while (i < numbers.length){
if (numbers[i] < 71){
console.log(numbers[i]);
}
i++;
}

Finding largest number in each sub-array of a 2D array? Javascript

I'm trying to return the largest number in each of the sub-arrays - but this is returning the first two values of each sub-array. Seems pretty simple and yet I can't find where I go wrong.
function largestOfFour (arr) {
let maxVal = 0
let newArr = []
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
maxVal = arr[i][j]
newArr.push(maxVal)
}
}
}
return newArr
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]))
This code returns the following: [ 4, 5, 13, 27, 32, 35, 37, 39, 1000, 1001 ]. Where am I going wrong? I don't want to use .sort()
The problem is, you push a new value whenever a new max value is found and not deleting the previously pushed value from the current set, you need to store the maxVal until the end of the inner loop and push the value afterwards, so you only push one value for each array, which is actually the biggest one
Your function should look similar to this:
function largestOfFour (arr) {
let maxVal = 0;
let newArr = [];
for (i = 0; i < arr.length; i++) {
// reset maxVal, for new set of numbers
maxVal = 0;
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
// new largest number found
maxVal = arr[i][j];
}
}
// push highest number found in set
newArr.push(maxVal);
}
return newArr
}
I don't know whether this is allowed, but it will get you the result:
const arr=[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
console.log(arr.map(a=>Math.max(...a)))
I prefer #CarstenMassmann's answer; however, just so you can understand how your code was in error, but very close, see this edit to the original attempt.
That inner conditional doesn't find the max of the sub-array, if finds the interim max. Don't push to your results inside the condition, finish iterating the sub-array and then push the best interim max...
function largestOfFour (arr) {
let maxVal = 0
let newArr = []
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
maxVal = arr[i][j]
// don't push here. maxVal is just the max *for now*
}
}
newArr.push(maxVal) // push here
}
return newArr
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]))

return the largest array between arrays

I am a beginner in Javascript and I should write a code to solve this problem: Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. and write this code can u tell me what is the problem him thnx:
function largestOfFour(arr) {
var pos = 0;
var max = 0;
var add = 0;
var sum = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (j === 4) {
sum[i] = add;
} else {
add = add + arr[i];
}
}
for (var i = 0; i < arr.length; i++) {
if (sum[i] > max) {
max = sum[i]
pos = i;
}
}
return arr[pos];
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
If you have no restrictions, you could take
Array#map for getting a new array with
Math.max for getting a maximum number and take
spread syntax ... for converting an array to parameters.
const largestOfFour = array => array.map(a => Math.max(...a));
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
For a more classic style, you could separate the functions, one for processing the outer array and one for getting a maximum value.
function max(array) {
var max = array[0];
for (let i = 1; i < array.length; i++) {
if (max < array[i]) max = array[i];
}
return max;
}
function largestOfFour(array) {
var result = [];
for (let a of array) result.push(max(a));
return result;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

Array summing method not working // javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to sum (ie. 4+15+10 etc... = total) the below array. I believe I'm using the right code but it doesn't seem to be working. Can someone take a look at it for me?
function beginhere() {
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var total =0
var i =0
for(i < arr.length; i++) {
total += arr[i][1];
}
document.getElementById("thismessage").innerHTML = i;
}
You need just the element, without another index, because you have an array with single values and not an array of arrays.
total += arr[i];
// ^^^
and the right start value for the for statement
for (i = 0; i < arr.length; i++) {
// ^^^^^
and you need to assign the total instead of the loop variable i.
document.getElementById("thismessage").innerHTML = total;
// ^^^^^
function beginhere() {
var arr = [4, 15, 10, 7, 6, 18, 1, 18, 8, 45, 55, 16, 9, 19, 11, 13, 14],
total = 0,
i;
for (i = 0; i < arr.length; i++) {
total += arr[i];
}
document.getElementById("thismessage").innerHTML = total;
}
beginhere();
<div id="thismessage"></id>
For loop syntax was wrong.its a for(i=0; i<length; i++)
Second problem was addition with array arguments. total += arr[i];
last one the you are not print the total value.you just print the increment .but the not use because is outside loop
function beginhere() {
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var total =0
var i =0
for(i=0; i < arr.length; i++) {
total += arr[i];
}
console.log(total);
}
beginhere();
Another method Array#reduce Arrow function simply use like this
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var res = arr.reduce((a,b) => a+b ,0)
console.log(res)
A few corrections:
You are missing a semicolon at the beginning of your for loop;
You don't need the extra [1] after your arr[i] access; and
You probably meant to set your content to total instead of i.
A few other suggestions:
Use textContent instead of innerHTML when you don't plan on inserting tags; and
Place var i = 0 inside of your for loop (this is common practice).
function beginhere() {
var arr = [4, 15, 10, 7, 6, 18, 1, 18, 8, 45, 55, 16, 9, 19, 11, 13, 14]
var total = 0
for (var i = 0; i < arr.length; i++) {
total += arr[i]
}
document.getElementById("thismessage").textContent = total
}
beginhere()
<p id="thismessage"></p>

largest no in array (js program) [duplicate]

This question already has answers here:
Creating an array consisting of the largest values of each sub-array does not work as expected
(4 answers)
Closed 6 years ago.
Return Largest Numbers in Arrays
//my code
function largestOfFour(arr) {
var largest=[];
for(var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++) {
if(arr[i][j] > largest){
largest[i]= arr[i][j];
}
}
}
return largest;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
//exp o/p
[27,5,39,1001]
//i m getting
[5,13]
I would do it in this way.
var largest=[];
a = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
for(var i = 0; i < a.length; i++){
largest.push(a[i].sort(function(a, b){return b-a})[0])
}
console.log(largest);
if(arr[i][j]>largest)
should be
if(arr[i][j]>largest[i])
Initialize your array too with some MIN value like 0
function largestOfFour(arr) {
var largest=[];
for(var i = 0; i < arr.length; i++){
largest[i] = 0;
for (var j = 0; j < arr[i].length; j++) {
if(arr[i][j] > largest[i]){
largest[i]= arr[i][j];
}
}
}
return largest;
}

Categories

Resources