0

im trying to store some object element from one array to another so lets say i have this array of objects

var Array = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];

and i want to store the first two object in this array to another array so it would like be

var SubArray =[{name:'Fadi'},{name:'Joseph'}];

thanks in advance for any help.

1
  • Ok, so SubArray = [Array[0],Array[1]], else you need to define you question a lot better. Commented Oct 10, 2014 at 15:25

2 Answers 2

4

You can use slice method for this:

var SubArray = Array.slice(0,2);

Please note that Array is reserved JS global object. You need to use different name for that variable. So your code should be for example:

var MyArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var SubArray = MyArray.slice(0,2);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for using a standard built-in function. MDN has a good documentation on Array and JS in general.
@antyrat if i want to add some new property like number to the sliced object can i do it directly with the slice or just loop on each object in the SubArray and add the new property.
Probably you need to loop
0

If you need conditional logic you want Array.filter(). If you know you always want the items by index then use slice as in antyrat's answer.

var originalArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var subArray = originalArray.filter(function(obj,index) {
    return obj.name=="Fadi" || obj.name=="Joseph";
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.