如何用字典对数组进行排序?[Javascript]



假设我有这样一个数组:

[
{num: 0, otherdatas: 'blah'},
{num: 5, otherdatas: 'blah'},
{num: 3, otherdatas: 'blah'},
{num: 8, otherdatas: 'blah'},
{num: 9, otherdatas: 'blah'},
{num: 4, otherdatas: 'blah'}
]

我想对这个数组排序。这样的:

[
{num: 0, otherdatas: 'blah'},
{num: 3, otherdatas: 'blah'},
{num: 4, otherdatas: 'blah'},
{num: 5, otherdatas: 'blah'},
{num: 8, otherdatas: 'blah'},
{num: 9, otherdatas: 'blah'}
]

如果数组是像[0, 5, 3, 8, 9, 4],排序将是容易的,但我有这些数字在字典。我能对这个数组做什么?

你有一个数组,该数组包含两个属性的对象:num和otherdata

  • -在数组上使用排序方法-sort将接受两个参数,它们分别指向数组中的当前项和下一项-u需要将这两个参数与a-b或b-a条件进行比较,从而得到升序或降序的结果-确保在比较时使用a.num和b.num,因为这里的a和b不是原语而是对象-a将返回一个新的数组,将数组存储在某个变量

const arr1 = [
{num: 0, otherdatas: 'blah'},
{num: 5, otherdatas: 'blah'},
{num: 3, otherdatas: 'blah'},
{num: 8, otherdatas: 'blah'},
{num: 9, otherdatas: 'blah'},
{num: 4, otherdatas: 'blah'}
]
const sortedArr = arr1.sort(function(a,b){
return a.num - b.num;
//OR
// return b.num-a.num ;
})

Array.prototype.sort接受一个可选参数compareFunction,这是一个定义排序顺序的函数。

应该接受两个参数a和b,这两个元素要进行比较,并返回一个数字,表示<如果B小于0,则a>如果大于0则为B,如果为0则为a = B。

你可以在MDN上找到它。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

您可以使用内置函数sort

对数组进行排序,答案是

let tempData = data.sort((a,b) => (a.num > b.num) ? 1 : ((b.num > a.num) ? -1 : 0))

输出:

[
{num: 0, otherdatas: 'blah'},
{num: 3, otherdatas: 'blah'},
{num: 4, otherdatas: 'blah'},
{num: 5, otherdatas: 'blah'},
{num: 8, otherdatas: 'blah'},
{num: 9, otherdatas: 'blah'}
]

最新更新