0
exports.getFbFriendsFromFbIdAndFbAccessTokenTest=function(id,token){

    var request = require('request');
    var urls = "https://graph.facebook.com/" + id + "/friends?access_token=" + token;

    request(urls, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            var output = JSON.parse(body);          
            output.sort(function(a,b){
                if (a.name > b.name)
                  return 1;
                if (a.name < b.name)
                  return -1;
                  // a must be equal to b
                return 0;
             });                

            console.log(output);            
        }           
    });

}

I want to sort the facebook friend's list in ascending order. Currently i am getting the following result in console:

`{ data: `

[ { name: 'xxx', id: '547dsad1' }, { name: 'xxx', id: '55324iii' }, { name: 'xxx', id: '55yyy' }, ........ ........

But it gives error that object output has no property sort. I have also used Array.prototype:

Array.prototype.sortByProp = function(p){
return this.sort(function(a,b){
return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
});
}

output.sortByProp('name');

But then it shows the same error that object output has not property sortByProp. Is there any other way to solve this problem?

2
  • are you sure output is 100% an array and not an object Array.isArray(obj) Commented Jan 30, 2014 at 11:51
  • Have you tried logging output = JSON.parse(body) to console to see what you're actually working with? It looks like the variable you're trying to "sort" isn't an array. (edit: looks like dark_ruby beat me to it) Commented Jan 30, 2014 at 11:57

1 Answer 1

3

output is an object, output.data is an array

Array.prototype.sortByProp = function(p){
  return this.sort(function(a,b){
    return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
  });
};

console.log(output.data.sortByProp('name'));
Sign up to request clarification or add additional context in comments.

8 Comments

Its not giving any result in the console.
it will not, to get result into console you need to console.log it, I updated my answer
TypeError: Object [object Object],[object Object].....[object Object],[object Object],[object Object],[object Object] has no method 'sortByProp'
can you run Array.isArray on an object you are trying to run sortByPropon, just to make sure it is an array?
It is returning false.
|

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.