按预定义编号对数组进行排序 [英] sorting array by predefined number

查看:64
本文介绍了按预定义编号对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有多维数组

var arr = [{
    "id": "1",
    "firstname": "SUSAN",
    "dezibel": "91"
}, {
    "id": "2",
    "firstname": "JOHNNY",
    "dezibel": "74"
}, {
    "id": "3",
    "firstname": "ANDREA",
    "dezibel": "67"
}];

如何用"dezibel"对它进行排序,而不是升序或降序,但最接近给定数字?例如

How can I sort it by "dezibel" but not ascending or descending, but closest to a giving number? For example,

var num = 78;

因此目标值是78.最终排序必须是:74、67、91.

so target value is 78. and final sorting must be: 74, 67, 91.

推荐答案

.sort 可选地带有一个函数.该函数一次获取2个值,并对其进行比较:

.sort optionally takes a function. The function takes 2 values at a time, and compares them:

  • 如果第一个值的排序应高于第二个值,则该函数应返回一个正数.
  • 如果第一个值的排序应低于第二个值,则该函数应返回负数.
  • 如果值相等,则函数应返回 0 .

因此,如果您想按 dezibel 升序排序,则可以

So, if you wanted to sort by dezibel in ascending order, you could do

arr.sort(function(a,b){
    return a.dezibel- b.dezibel;
});

但是,您想要按 dezibel 与某个数字的距离进行排序.要从 78 dezibel 值中找到差异的大小,请取差异的绝对值:

However, you want to sort by dezibel's distance from some number. To find the magnitude of the difference from 78 and the dezibel value, take the absolute value of the difference:

Math.abs(78 - a.dezibel)

现在,如果我们要基于每个对象的值进行排序,则可以对 a 进行 Math.abs 调用的区别b :

Now, if we want to sort based on that value for each object, we can take the difference of that Math.abs call for both a and b:

arr.sort(function(a,b){
    return Math.abs(78 - a.dezibel) - Math.abs(78 - b.dezibel);
});

这篇关于按预定义编号对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆