How does while loop work without a condition? - javascript

I understand that it's removing the first 3 elements of the array and adding them to the new array. But how does the function continue to add ensuing chunks of the array to the new array variable?
How does the while loop work without proper conditions?
How does it work in collaboration with splice() here?
function chunkArrayInGroups(arr, size){
let newArr = [];
while(arr.length){
newArr.push(arr.splice(0, size))
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

The condition is while(arr.length). The while loop will run while that condition is truthy. In JavaScript every condition is truthy unless it is one of the following:
false
0 (zero)
'' or "" (empty string)
null
undefined
NaN (e.g. the result of 1/0)
In your case the while loop will run while the array has elements in it (arr.length is greater than zero), because if the arr.length is zero the while loop will stop executing.
arr.splice on the other hand is removing one element from arr every time it is executed (it is changing the arr length). So when there are no elements left in the arr (because arr.splice removed them all) the while loop will stop.

Conditions in js are either "truthy" or "falsy", for numbers everything except 0 is "truthy", 0 is "falsy". That means that the loop runs until the array is empty, its length 0 and therefore falsy.
if(0) alert("never");
if(1) alert("always");
let i = 3;
while(i) console.log(i--);

The while loop is gonna keep going until the original array is empty. Splice will remove the selected elements from the original array and while will continue until the last elements are removed.
Also, as the elements are removed from the original array, they are being pushed (added) to the new array

Related

Why is this for loop not removing all repetitions of arrays?

Backset is an array of arrays, I am trying to filter out any arrays which contain a repetition of elements, such as an array with 2 ones. I would like to remove these from the Backset array.
However this is not happening and some arrays in backSet such as [1,2,2] stay in backSet.
for(z=0; z<backSet.length; z++){
backSet[z].sort();
tempBackSort = [];
for(k=0; k< backSet[count].length; k++){
if(tempBackSort.includes(backSet[count][k])){
backSet.splice(backSet.indexOf(backSet[count]),1);
kon = 0;
continue;
} else{
tempBackSort.push(backSet[count][k]);
kon = 1;
}
}
if(kon===1){
count++;
}
backSet[z].sort();
}
There are several issues:
Where you have continue now it accomplishes nothing. You need break, so the inner loop is exited
You try to overcome the problem of iterating over an array where elements are sometimes removed by using count, but:
count is not initialised
You still have code that works with backSet[z] instead of backSet[count]
It would have been easier to just decrease z when an element is removed, or even better: to let the outer loop iterate backwards from end to start -- then you don't need to adjust any index.
Variables are implicitly declared as globals: this is bad practice. Define your variables with let or const.
By sorting the inner arrays, you mutate the original data. This might be OK for your case, but still it is maybe surprising for code that depends on this piece of code.
Sorting is also not the most efficient way to find duplicates. Instead of pushing values in tempBackSort, put them in a Set (which cannot contain duplicates) and compare its size with the original array: if their sizes are not the same, then there are duplicates.
Instead of splicing inside a loop (which is the cause of your trouble), use the array method filter which returns the filtered array.
Here is how it could be coded:
backSet = backSet.filter(arr => (new Set(arr)).size == arr.length);

How while(array.length) works without any increment/decrement [duplicate]

I understand that it's removing the first 3 elements of the array and adding them to the new array. But how does the function continue to add ensuing chunks of the array to the new array variable?
How does the while loop work without proper conditions?
How does it work in collaboration with splice() here?
function chunkArrayInGroups(arr, size){
let newArr = [];
while(arr.length){
newArr.push(arr.splice(0, size))
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
The condition is while(arr.length). The while loop will run while that condition is truthy. In JavaScript every condition is truthy unless it is one of the following:
false
0 (zero)
'' or "" (empty string)
null
undefined
NaN (e.g. the result of 1/0)
In your case the while loop will run while the array has elements in it (arr.length is greater than zero), because if the arr.length is zero the while loop will stop executing.
arr.splice on the other hand is removing one element from arr every time it is executed (it is changing the arr length). So when there are no elements left in the arr (because arr.splice removed them all) the while loop will stop.
Conditions in js are either "truthy" or "falsy", for numbers everything except 0 is "truthy", 0 is "falsy". That means that the loop runs until the array is empty, its length 0 and therefore falsy.
if(0) alert("never");
if(1) alert("always");
let i = 3;
while(i) console.log(i--);
The while loop is gonna keep going until the original array is empty. Splice will remove the selected elements from the original array and while will continue until the last elements are removed.
Also, as the elements are removed from the original array, they are being pushed (added) to the new array

Javascript chunky monkey algorithm code break down?

I need a help on breaking how does this code works?
function chunkArrayInGroups(arr, size) {
var newArr = [];
while (arr.length) {
newArr.push(arr.splice(0,size));
}
return newArr;
}
chunkArrayInGroups(["a","b","c","d"],2);
I dont understand how while(arr.length) gets stop and what this whole code is doing. Please break this down.
Array.splice modifies the original Array. When it is called inside while loop, It keeps shortening the original array and after a few iterations, arr.length becomes 0 and evaluates to false.
arr.splice(0,size)
Array.splice will remove elements from index 0 up till size and return them as a new array.
newArr.push(arr.splice(0,size));
The returned array is then pushed to newArr.
while (arr.length)
Array.splice will also mutate the original array so the arr will eventually becomes empty and the loop will end.
while (arr.length) executes until the array is empty, because when it's empty, arr.length equals 0 and it's treated as false.
while array count is "available" push into newArr (and also remove the certain item of it from the root array) when all is done, return it

Inconsistent results when using forEach and .shift()

So here are two fiddles:
Fiddle 1
Fiddle 2
When using forEach and then array shift inside the loop the output results in duplicates but if I use a regular for loop and use the shifted return as output it works correctly.
So the only difference between the two are:
var queueSize = testArray.length;
if (queueSize > 0) {
testArray.forEach(function (loopData) {
jQuery('.js-target').append(loopData+'<br>');
testArray.shift();
});
}
Compared to:
for (var i = 0; i < testArray.length; i++) {
var d = testArray.shift();
jQuery('.js-target').append(d+'<br>');
}
To me the first one should work just as well as the second one. (The data is added to testArray with push i.e. to the end of the array). Is it something I'm not understanding with the shift function?
The shift method will remove the element at the start of the array. So your array in the second example is being shortened at each iteration.
The shift method removes the element at the zeroeth index and shifts
the values at consecutive indexes down, then returns the removed
value. If the length property is 0, undefined is returned.
See the MDN docs for a full overview.
You may want to read this explanation in MDN it's really nice
The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. forEach() does not make a copy of the array before iterating.
var words = ['one', 'two', 'three', 'four'];
words.forEach(function(word) {
console.log(word);
if (word === 'two') {
words.shift();
}
});
// one
// two
// four
If you change the elements of the array (as opposed to their values) during a forEach loop, it is going to behave differently to a regular for loop.
From MDN:
The range of elements processed by forEach() is set before the first
invocation of callback. Elements that are appended to the array after
the call to forEach() begins will not be visited by callback. If the
values of existing elements of the array are changed, the value passed
to callback will be the value at the time forEach() visits them;
elements that are deleted before being visited are not visited.

Javascript - array index issue in non sparse array

non sparse array are contiguous in nature and from 0 to length-1, all index should return true for 'in' operator. It should be true also for empty element.
obj1 = {x:1,y:2};
obj2 = Object.create(obj1);
obj2.z = 5;
var arr = [obj1,obj2,1,,2];
console.log(arr.length); //5
console.log(3 in arr);//false
index 3 is valid.
Why is it returning false?
Note: I am using latest firefox.
It should return false only for sparse array which doesn't have a specified index number 3.
Update: index 3 is valid so it should return true. in operator doesn't validate value of at the indexed position, it just validate the validity of index not the value
3 in arr is false because arr[3] is never set (and thus the array is indeed sparse).
Note the double comma in
var arr = [obj1,obj2,1,,2];
– if you make that
var arr = [obj1,obj2,1,2];
then 3 in arr becomes true.
See page 63 in the specification:
Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the
element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another
comma), the missing array element contributes to the length of the Array and increases the index of
subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array,
that element does not contribute to the length of the Array.
– in other words, the behavior of your code is identical to
var arr = [obj1, obj2, 1];
arr[4] = 2;
Javascript is evaluating the value which is undefined. Undefined is falsy.
Array always have 0 based index, in your array 4th element (3 by index) is not set to any value.
Refere this
From the link
Here is what is falsy in JavaScript:
false
null
undefined
The empty string
''
The number 0 The number NaN (yep, 'Not a Number' is a number, it is a special number)
Everything else is truthy, and that includes Infinity (which is
another special number, like NaN), and all Object objects and Array
objects, empty or not.

Categories