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/

6
  • @ScottSelby Yes, absolutely.
    – VisioN
    Commented Apr 3, 2013 at 14:45
  • that's some pretty sexy code :) , still learning js , thanks Commented Apr 3, 2013 at 14:46
  • @VisioN strictly speaking that's Array.prototype.map - Array.map would be a (non-existent) class method, not an instance method.
    – Alnitak
    Commented Apr 3, 2013 at 14:49
  • 1
    @Alnitak Yes, I have used Array.map just to be shorter.
    – VisioN
    Commented Apr 3, 2013 at 14:51
  • suggest you use myArray.map or write it in full to avoid ambiguity
    – Alnitak
    Commented Apr 3, 2013 at 14:54
1

Try to use projection method .map()

var listOfFriendsUIDs = listOfFriends.map(function(f){ return f.uid;});
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;

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.