Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Arnold Sanglepp
12,168 PointsCreating a loop to find the last number from an array
Hi!
I am in a pickle with a little task. I need to sort out a number from an array by deleting and skiping other numbers.
Basically I have an array with numbers from 1 to 100. I need to delete numbers starting from 1 and then skip the amount of numbers, that have been deleted so far.
For example, When I delete nr 1 then I skip 1 number and then delete nr 2. Then delete number 3 and skip 4 & 5.
Is there a way to make a loop, that finds that last number?
My code so far
//creating an array form 1 to 100
var numbers=[];
for(var i = 1; i <= 100; i++) {
numbers.push(i);
};
//finding the last number
for(var i = 0; numbers.length = 1; i++ ){
if(i > numbers.length){
i = 0;
}
numbers.splice(i);
}
// And the other version of the loop
//finding the last number
for(var i = 0; numbers.length = 1; i++){
numbers.splice(0 + i);
}
console.log(numbers);
Can some one help me with the code of give some references?
Thanks
Arnold Sanglepp
12,168 PointsOh sorry. My typo. Yes, the second number to delete should be 3 and then 6
1 Answer
Steven Parker
243,656 PointsIf I understand that you just want to find the number, and not actually delete anything from an array, this should do:
var n = 1;
var count = 0;
var last;
while (n <= 100) {
last = n;
n += ++count + 1;
}
console.log(last);
You get a sequence of 13 numbers that starts with 1, 3, 6, 10... and ends with 91.
Steven Parker
243,656 PointsSteven Parker
243,656 PointsYou said, "When I delete nr 1 then I skip 1 number and then delete nr 2". But if you skip a number, wouldn't the one skipped be 2, and the second one deleted be 3?