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

}

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/

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;});

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;

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.