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
Related
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);
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
function filteredArray(arr, elem) { let newArr = [];
Loops through every element of the nested array.
for (let i=0;i<arr.length;i++){
for (let j=0;j<arr[i].length;j++){
If the value on the iteration is equal to the argument passed, it is supposed to set a variable x to be equal to the value of the nested array during the ongoing iteration
if (arr[i][j]==elem){
let x = indexOf(arr[i][j]);
It is supposed to remove the element with index equal to the variable x.
arr[i][j].splice(x,1);
Then it is supposed to push the remained of the nested array to the new array and then subsequently return the new array.
newArr[i].push(...arr[i][j]);
}
}
}
console.log(newArr);
return newArr;
}
HOWEVER THERE IS AN ERROR THAT SAYS 'indexOf is not defined'
I don't understand why it doesn't work. It return indexOf as undefined for every iteration. Please take a look at comments.
Please share your opinion on my code if you don't mind.
indexOf is an array/string method and can be called on an array like array.indexOf(element). In your case your you need to pass the array.
Also you may skip the indexOf because here variable i and j will give the relevant index of the parent and nested array
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
Is this intended behavior? I would expect an empty array to be returned here.
JavaScript
let arr = [1];
console.log(arr.splice(0, 1))
Console
1
Because it returns what was removed, which is [1] in your case. arr will be empty after the call.
See example:
let arr = [1];
arr.splice(0, 1);
console.log(arr);
Array.prototype.splice() returns an array of the deleted elements.
Your are logging the returned value of the operation not the current state of the array.
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
Reference
The syntax of this method is:
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)
You are using the second syntax and passing 0 as start and 1 as deleteCount that means you would like to start at 0th index and delete 1 item (not 1 as value in array).
This method returns an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
So, in this case the result is [1] i.e. an array with value of 1 that is the item you just deleted.
I ran into this question when I was trying to achieve a function in mini-program. A solution is to check the array's length before using the function splice. For example:
if(imgList.length > 1){
imgList.splice(index, 1);
else{
imgList = []
}
You can try to solve it like that.