Using Continue in a While loop in Javascript [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 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++;
}

Related

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]]))

Function to left rotate a given array item n position to left - JavaScript

I'm doing some exercises on JavaScript and I came into a question that asks to rotate arrays item to the left with a given n rotation steps. The exercises are tested with Jasmine. Tried several method but none are meeting the precondition:
it("Arrays: Rotation Gauche", function () {
// DESCRIPTION:
// A left rotation operation on an array shifts each element
// from the array to the left. For example, if left rotations are
// done on the array [1,2,3,4,6], the array would become [3,4,5,1,2]
//
// Given an array of integers a, do n left rotations on
// the array. The function returns the updated array.
function rotateLeft(a, n) {
// TODO: implement the function as described in DESCRIPTION
let len = 0,j=0
var b =[]
len = a.length
for (let i = n; i < len; i++){
b[j] = a[i]
j++
}
for (let i = 0; i < n; i++){
b[j] = a[i]
j++
}
return b;
}
// Jasmin unit tests
let input = [1, 2, 3, 4, 6];
let expected = [3, 4, 5, 1, 2];
expect(rotateLeft(input, 4)).toBe(expected);
input = [41, 73,89,7,10,1,59,58,84,77,77,97,58,1,86,58,26,10,86,51];
expected = [7,97, 58, 1, 86, 58, 26, 10, 86, 51, 41, 73, 89, 7, 10, 1, 59, 58, 84, 77]
expect(rotateLeft(input, 10)).toBe(expected);
input = [98,67,35,1,74,79,7,26,54,63,24,17,32,81];
expected = [26, 54, 63, 24, 17, 32, 81, 98, 67, 35 ,1 ,74, 79, 7]
expect(rotateLeft(input, 7)).toBe(expected);
});
My last attempt is below the TODO comment.
And obviously the tests aren't passing. I tried several approaches without success. It's just an exercise, so I would like some guidance.
Thanks

Check for multiple numbers in an array [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 3 years ago.
Improve this question
I need to create a function that checks all numbers in an array and print them out.
My idea was something similar to this:
var array = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99];
var string = "";
var len = array.length;
After declaring the variables, i start to loop them:
for (var i = 0; i < len; i ++) {
for (var j = 0; j < len; j ++) {
//console.log(array[i], array[j]);
}
}
Console prints me value in this order:
3 3
3 6
3 67
. .
6 3
6 6
6 67
. .
I thought to create a if statement checking if array[i] is equal to array[j] then pushing the content in a new string.
You need to iterate in the outer loop until the element before the last item and in the inner loop start from the actual index plus one, to prevent to check the same element.
If duplicate is found, push the value to the duplicates array.
var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
len = array.length,
i, j,
duplicates = [];
for (i = 0; i < len - 1; i++) {
for (j = i + 1; j < len; j++) {
if (array[i] === array[j]) duplicates.push(array[i]);
}
}
console.log(duplicates);
A shorter approach by using a Set
var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
found = new Set,
duplicates = array.filter(v => found.has(v) || !found.add(v));
console.log(duplicates);
You can also use Set with Array.filter and Array.indexOf:
let data = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99]
let r = new Set(data.filter((v, i, a) => a.indexOf(v) !== i))
console.log(Array.from(r))
The idea is to filter the items to those who have multiple indexes found and then add them to the Set. Since Set stores unique items only it will take care of the duplicates and you get the final result.
We take advantage of the fact that Array.filter provides 3 arguments to the iteratee function - value (v), current index (i) and the actual array (a).

javascript infinite loop error multidimensional array sort [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 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]]));

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