Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

javascript - Sort array of objects

I have an array of object literals like this:

var myArr = [];

myArr[0] = {
   'score': 4,
   'name': 'foo'
}

myArr[1] = {
   'score': 1,
   'name': 'bar'
}

myArr[2] = {
   'score': 3,
   'name': 'foobar'
}

How would I sort the array so it ascends by the 'score' parameter such that it would change to:

myArr[0] = {
   'score': 1,
   'name': 'bar'
}

myArr[1] = {
   'score': 3,
   'name': 'foobar'
}

myArr[2] = {
   'score': 4,
   'name': 'foo'
}

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try myArr.sort(function (a, b) {return a.score - b.score});

The way the array elements are sorted depends on what number the function passed in returns:

  • < 0 (negative number): a goes ahead of b
  • > 0 (positive number): b goes ahead of a
  • 0: In this cases the two numbers will be adjacent in the sorted list. However, the sort is not guaranteed to be stable: the order of a and b relative to each other may change.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...