Remove the first element of an array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Remove the first element of an array

My task is to remove the first element of an empty array every time its length reaches 2500. The problem with my code is every time it execUtes iy displays a random number for the first element.

28th Jun 2017, 6:23 PM
Manik Tafralian
Manik Tafralian - avatar
3 Answers
+ 4
Take a look at this Manik: https://code.sololearn.com/WyQ0w45VhWx1/#js I cleaned up your code some, and have it properly displaying the data so you can see what's actually going on with your array. As you can see, if you use shift OR splice, it shifts all of the other elements over. This is when you end up getting a different number for the first element after you removed the first element. By the way, I changed the 2500 to 50 for testing purposes. If you use the code I posted, just change maxArr from 50 to 2500. Hope this helps. Quick view: var empArr=[]; var maxArr = 50; var s; for(var i=0; i<maxArr; i++) { empArr.push(Math.round(Math.random() * 50)); document.write("Element " + i + ": " + empArr[i] + "<br>"); } document.write("<br>"); arr(); function arr(){ if(empArr.length>=50){ empArr.shift(); } for(var i=0; i<empArr.length; i++) { document.write("NEW Element " + i + ": " + empArr[i] + "<br>"); } }
28th Jun 2017, 8:17 PM
AgentSmith
+ 3
int arr = []; if(arr.length>=2500){ arr.splice(0,1); } 0 is the index from which you have to remove the element and 1 is the amount of elements to remove . Therefore it removes 1 element starting from the index 0 i.e. number at index 0 .
28th Jun 2017, 7:14 PM
Utkαrsh
Utkαrsh - avatar
0
html> <head> <title>Empty array</title> </head> <body> <script> var empArr=[]; var j=empArr.length; var s; for(var i=1,j=2500;i<j;i++) { var rand=empArr.push(Math.round(Math.random() * 2500)) console.log(rand); } function arr(){ for(var i=1;i<j;i++) {if(j>=2500){ s=empArr.shift(); }return empArr[0]; } } document.write(arr()); </script> </body> </html>
28th Jun 2017, 6:26 PM
Manik Tafralian
Manik Tafralian - avatar