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

JavaScript

objects, arrays , deleting , adding

is there a way of getting an element from an array , specifically an object, placing it in another array of objects and deleting the copied object from the original array. The array methods return an array containing the object as a result which I am having some trouble manipulating and I am getting strange results/errors in my code that I cannot figure out. I need to be able to access the object itself and place it in another array, any insight would be greatly appreciated, thanks

1 Answer

The key is to access a property on the object, so...

var originalArr = [obj1,obj2,obj3];
var newArr = [];

//assuming each obj has a 'name' key, and obj1's name value='Michael'
originalArr.forEach(function(val,i,arr) {
    if(val.name ==='Michael') {
        //add it to the new array
        newArr.push(val);

        //delete it from the old array
        originalArr.pop(val);
    }
});

It's definitely worth looking into the lodash and underscore libraries as they have a lot of these collection methods built in.