I brought the list of friends from the contact, and brought them to the age. How do I now sort them by age descending?

I can not guess at all.

http://plnkr.co/edit/S6smJK2teK9TNegdQgZv?p=preview

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script src="http://vk.com/js/api/openapi.js"></script> <script> function foo() { VK.init({ apiId: 5580872 }); VK.Auth.login(function(response){ if(response.session){ VK.api('friends.get', {'user_id' : '26291131', 'fields' : 'bdate'}, response => { if(response.error){ alert(response.error.error_msg); } else{ let userData = response.response; var minAge = 0; var arrUser = [] var arrAge; var now = new Date(); var god = now.getFullYear() for(var h = 0; h < userData.length; h++){ arrUser.push(userData[h].first_name + ' ' + userData[h].last_name) if(typeof userData[h].bdate == 'string' && userData[h].bdate.split('.')[2]){ arrAge = userData[h].first_name + ' ' + userData[h].last_name + ' ' + (god - parseInt((userData[h].first_name + ' ' + userData[h].last_name + ' ' + userData[h].bdate.split('.')[2]).split(' ')[2])) console.log(arrAge.split(' ').sort()) } } } }); } else{ alert('Не удалось авторизироваться') } }, 2); } foo() </script> </body> </html> 

now this kind

  var arr = [ ['26', 'firstname1', 'lastname1'], ['14', 'firstname2', 'lastname2'], ['22', 'firstname3', 'lastname3'], ['23', 'firstname4', 'lastname4'], ['20', 'firstname5', 'lastname5'] ] 

How to make this?

 var arr = [ ['26', 'firstname1', 'lastname1'], ['23', 'firstname4', 'lastname4'], ['22', 'firstname3', 'lastname3'], ['20', 'firstname5', 'lastname5'], ['14', 'firstname2', 'lastname2'] ] 
  • And why is the link to http://plnkr.co/edit/S6smJK2teK9TNegdQgZv?p=preview if the window pops up? Could not log in ? Maybe then return the json attach? - Alexey Shimansky
  • Write here an example of an object to be sorted - Vasya Shmarovoz
  • Updated the topic. Revise please. - DivMan
  • one
    The previous question has already given the answer - and it works. If it doesn't work in your code. means either your code is different. or your data is different. - Grundy
  • one
    @DivMan why did you ask the question again? - Alex

1 answer 1

There is a sort method - sorts the elements of an array in place and returns a sorted array.

Syntax

 arr.sort([compareFunction]) 

where, compareFunction is an optional parameter. Specifies the function that determines the sort order.

 var arr = [ ['26', 'firstname1', 'lastname1'], ['14', 'firstname2', 'lastname2'], ['22', 'firstname3', 'lastname3'], ['23', 'firstname4', 'lastname4'], ['20', 'firstname5', 'lastname5'] ]; arr.sort(function(a,b){ return a < b; // по убыванию // return a[0] > b[0]; // по возрастанию }); arr.forEach(function(el){ console.log(el); });