最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Array sort by last name, first name - Stack Overflow

programmeradmin14浏览0评论

I have the following array in JavaScript, I need to sort them by last name.

var names = [Jenny Craig, John H Newman, Kelly Young, Bob];

Results would be:

Bob, 
Jenny Craig, 
John H Newman, 
Kelly Young 

Any examples on how to do this?

I have the following array in JavaScript, I need to sort them by last name.

var names = [Jenny Craig, John H Newman, Kelly Young, Bob];

Results would be:

Bob, 
Jenny Craig, 
John H Newman, 
Kelly Young 

Any examples on how to do this?

Share Improve this question edited Jun 11, 2014 at 22:00 mucio 7,1191 gold badge22 silver badges36 bronze badges asked Jun 11, 2014 at 21:55 Jeffrey MessickJeffrey Messick 991 gold badge1 silver badge5 bronze badges 4
  • 1 do you want to sort them alphabetically, or just put those without last names first? – James G. Commented Jun 11, 2014 at 22:01
  • 1 Is Bob a first or a last name? Does the H belong to the first or the last name? – Bergi Commented Jun 11, 2014 at 22:28
  • Amir answer worked for me. – Jeffrey Messick Commented Jun 11, 2014 at 22:30
  • @Jeffrey: if Amir's answer worked for you, then please do consider accepting it :) – David Thomas Commented May 14, 2018 at 22:45
Add a comment  | 

3 Answers 3

Reset to default 11

Try this:

const names = ["John H Newman", "BJenny Craig", "BJenny Craig", "Bob", "AJenny Craig"];

const compareStrings = (a, b) => {
  if (a < b) return -1;
  if (a > b) return 1;

  return 0;
}

const compare = (a, b) => {
  const splitA = a.split(" ");
  const splitB = b.split(" ");
  const lastA = splitA[splitA.length - 1];
  const lastB = splitB[splitB.length - 1];

  return lastA === lastB ?
    compareStrings(splitA[0], splitB[0]) :
    compareStrings(lastA, lastB);
}

console.log(names.sort(compare));

function lastNameSort(a,b) {
    return a.split(" ").pop()[0] > b.split(" ").pop()[0]
};
names.sort(lastNameSort);

This was inspired by this answer.

Try This:

function sortContacts(names, sort) {

    if(sort == "ASC")
        return names.sort(lastNameSort);    
    else
        return names.sort(lastNameSortDesc);    

}

//ASCENDING SORT
function lastNameSort(a,b) {  
    if(a.split(" ")[1] > b.split(" ")[1])
      return 1;
    else
      return -1;
};

//DESCENDING SORT
function lastNameSortDesc(a,b) {  
    if(a.split(" ")[1] > b.split(" ")[1])
      return -1;
    else
      return 1;
};

For your knowledge, the Javascript's SORT function allows us to send a "Compare" method in the parameter. In the above code, it's using the same technique.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

发布评论

评论列表(0)

  1. 暂无评论