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
Eric Washington
iOS Development with Swift Techdegree Student 21,884 PointsMake a function that copies an array, ONLY accepting the items that are numbers. "IT SHOULD RETURN A NEW ARRAY"
"IT SHOULD RETURN A NEW ARRAY" var newArray = numbersOnly([1, "apple", -3, "orange", 0.5]); // newArray is [1, -3, 0.5]
Hint: Use typeof to determine type (ex: typeof 24 === "number" would be true)
Can someone help me wit this problem please? Been stuck on it for hours.
1 Answer
Alex Arzamendi
10,042 PointsThis one is a little tricky but simple if we understand the values that are being passed on into the function items.
I do not know what excercise this one is but I will give it a go with a quick script i came up with that I believe solves this problem, read it and see if it helps, it might be the code you are looking for.
var numbersOnly = function(items) {
// placeholder array that will hold all the numeric values after the type has been determined
var placeHolder = [];
// a simple for loop that will go through each one of the items and check what it is, we know how to loop based on the number of items
for(var i = 0; i < items.length; i++) {
// if the item at position i is of numeric type we push the item into the placeholder array, this does not disturb position
if (typeof items[i] == "number"){
placeHolder.push(items[i]);
}
}
// finally, we return the placeHolder array since it has all of its values sorted out
return placeHolder;
}
// tests
var tests = numbersOnly([1, 2, 3, "number", "cuatro", 6]);
console.log(tests);
Let us know if this works!
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsCan you post more of your code? Also link to the challenge?