0

I have an array listOfFriends of objects that contain [{"name" : "fName lName", "uid" : "0102030405"}], ...

I want to cut down the size of this array , since I only need the uids , so I would like to make another array with only the uids

var listOfFriends, listOfFriendsUIDs;
//listOfFriends gets filled
for(var i = 0; i < listOfFriends.length; i++){
 listOfFriendsUIDs[i].uid = listOfFriends[i].uid; // this line isn't working
 //listOfFriendsUIDs is still undefined untill the start of this loop
}
asked Apr 3, 2013 at 14:39

3 Answers 3

4

You can use Array.prototype.map to create new array out of IDs:

var listOfFriendsUIDs = listOfFriends.map(function(obj) { return obj.uid; });

Check the browser compatibility and use shim if needed.

DEMO: http://jsfiddle.net/x3UkJ/

answered Apr 3, 2013 at 14:42
Sign up to request clarification or add additional context in comments.

6 Comments

@ScottSelby Yes, absolutely.
that's some pretty sexy code :) , still learning js , thanks
@VisioN strictly speaking that's Array.prototype.map - Array.map would be a (non-existent) class method, not an instance method.
@Alnitak Yes, I have used Array.map just to be shorter.
suggest you use myArray.map or write it in full to avoid ambiguity
|
1

Try to use projection method .map()

var listOfFriendsUIDs = listOfFriends.map(function(f){ return f.uid;});
answered Apr 3, 2013 at 14:43

Comments

0

listOfFriendsUIDs[i] is not defined, so you can't access its uid property. You either need:

// creates an array of UID strings: ["0102030405", ""0102030405", ...]
listOfFriendsUIDs[i] = listOfFriends[i].uid;

or

// creates an array of objects with a uid property: [{uid:"0102030405"}, ...]
listOfFriendsUIDs[i] = {}
listOfFriendsUIDs[i].uid = listOfFriends[i].uid;
answered Apr 3, 2013 at 14:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.