I am working on a CodeWars kata that involves multidimensional arrays. I have an array with three elements. Each element is an array with a name (string) and a sum (number). I am checking the numbers. If they exceed a certain amount, I want to remove the sub array with that number and put it at the end of the array. I used splice() and push().
In a test case that had a sub array that had to be moved, the sub array was pushed to the end of the parent array. But, it had an extra set of brackets. I was wondering why this happened. Is JavaScript automatically adding the brackets when the push takes place because the parent array has only sub arrays as elements?
Here is a link to some screenshots of the Chrome Dev Tools and one from CodeWars. I combined them into one image. The sub array at index 2 in the pop out window shows the sub array at the end that was moved/pushed in the first screenshot. The second screenshot shows the expanded view. The final screenshot I am attaching is the result shown in CodeWars where you can see the double brackets on the last sub array.
I cannot get the image to upload. So, here is a link to it online. https://sta.sh/01tp7y7zaayi
Here is the section of code where this is happening. I included the sort. But, I don't think it is affecting anything.
Note: I had a loop to go through the three elements to check them where the comment is located. But, I removed it because one shouldn't loop through an array and make changes to that array. I am coding a map() method for this to return a new array. But, I noticed that the double brackets were appearing. So, I didn't finish the map() part. I am trying to figure out what is happening in that splice() / push() section first.
var arrNew = [["Ben", sumBen], ["Amy", sumAmy], ["Sam", sumSam]];
arrNew.sort(function (a,b) {
if (a[1] < b[1]) return 1;
if (a[1] > b[1]) return -1;
if (a[0] > b[0]) return 1;
if (a[0] < b[0]) return -1;
return 0;
});
// If someone's score is over 21, move them to the back.
var forMoving = arrNew.splice(0, 1);
arrNew.push(forMoving);
Use Array.concat
instead of push to concat arrays.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.