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
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
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
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.
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.
I want to iterate over two arrays at the same time, as the values for any given index i in array A corresponds to the value in array B.
I am currently using this code, and getting undefined when I call alert(queryPredicates[i]) or alert(queryObjects[i]).
I know my array is populated as I print out the array prior to calling this.
//queryPredicates[] and queryObjects[] are defined above as global vars - not in a particular function, and I have checked that they contain the correct information.
function getObjectCount(){
var variables = queryPredicates.length; //the number of variables is found by the length of the arrays - they should both be of the same length
var queryString="count="+variables;
for(var i=1; i<=variables;i++){
alert(queryPredicates[i]);
alert(queryObjects[i]);
}
The value of the length property of any array, is the actual number of elements (more exactly, the greatest existing index plus one).
If you try to access this index, it will be always undefined because it is outside of the bounds of the array (this happens in the last iteration of your loop, because the i<=variables condition).
In JavaScript the indexes are handled from 0 to length - 1.
Aside of that make sure that your two arrays have the same number of elements.
If queryPredicates does not have numerical indexes, like 0, 1, 2, etc.. then trying to alert the value queryPredicates[0] when the first item has an index of queryPredicates['some_index'] won't alert anything.
Try using a for loop instead:
stuff['my_index'] = "some_value";
for (var i in stuff)
{
// will alert "my_index"
alert(i);
// will alert "some_value"
alert(stuff[i]);
}
Arrays in JS are zero based. Length is the actual count. Your loop is going outside the bounds of the array.