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 trialGena Israel
2,047 Pointshow do you remove something from an array and put it into a new var array...
i don't think i did this exercise correct even though i passed
var orderQueue = ['1XT567437','1U7857317','1I9222528'];
orderQueue.shift();
var shipping = '1XT567437';
var cancelled=
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
1 Answer
William Olojede
Courses Plus Student 2,752 PointsThere are a couple of ways you can go about doing this depending on the position of the item in the array you want to remove and insert into another array.
if you want to remove the first item, you can use .shift()
to remove and then .push()
to insert to the end of another array.
e.g
var a = [1, 2, 3];
var b =[]; // empty array where you want to insert the first item in a(1)
var c = a.shift(); // c holds the value(1) returned by .shift()
b.push(c)
console.log(b); // => [1]
console.log(a); // => [2, 3]
if you want to remove the last item, you can use .pop()
to remove and then .push()
to insert to the end of another array.
e.g
var a = [1, 2, 3];
var b =[]; // empty array where you want to insert the last item in a(3)
var c = a.pop(); // c holds the value(3) returned by .pop()
b.push(c)
console.log(b); // => [3]
console.log(a); // => [1, 2]
Alternatively, you can use .slice() which allows you to choose a start and end position