获取 JSON 数组中的最大值
Posted
技术标签:
【中文标题】获取 JSON 数组中的最大值【英文标题】:Getting max value(s) in JSON array 【发布时间】:2014-05-21 21:22:33 【问题描述】:我正在尝试创建一个 javascript 函数,该函数从外部 JSON 中的数组获取信息,然后获取其中一个 JSON 变量的最大值(或前 5 个值)。对于此示例,假设我想获取值“ppg”的最大值。这是数组的一个小样本:
[
"player" : "Andre Drummond",
"team" : "Detroit Pistons",
"ppg" : "15.4",
"rpg" : "11.6",
"apg" : "2.4",
"bpg" : "1.6",
"spg" : "0.8",
"3pg" : "0.1"
,
"player" : "Anthony Davis",
"team" : "New Orleans Pelicans",
"ppg" : "16.4",
"rpg" : "13.6",
"apg" : "2.6",
"bpg" : "3.5",
"spg" : "1.2",
"3pg" : "0.1"
,
"player" : "Carmelo Anthony",
"team" : "New York Knicks",
"ppg" : "27.4",
"rpg" : "5.4",
"apg" : "4.5",
"bpg" : "1.1",
"spg" : "1.5",
"3pg" : "1.6"
]
通过数组获取最大值然后从该值获取值“玩家”和“团队”的最佳方法是什么?该页面将是交互式的,因为我将有一个下拉菜单栏,允许查看者在“玩家”和“团队”之外的六个 JSON 值之一之间进行选择。提前致谢!
【问题讨论】:
重复***.com/questions/4020796/…请查看解决方案 也许我的问题是我是 json 新手,如果它是一个 javascript 数组,我想我可以找出代码。与此同时,我正在编写代码,看看我是否可以自己解决。 @LesPaul - JSON 只是一种用于表达一些 javascript 数据结构的文本格式。一旦你在 JSON 上调用JSON.parse()
,它就是普通的 javascript。
为了将来参考,任何想尝试将外部 JSON 文件加载到变量中的人都可以在这里查看:***.com/questions/2177548/load-json-into-variable
【参考方案1】:
只需循环遍历数组,并随时跟踪最大值:
function getMax(arr, prop)
var max;
for (var i=0 ; i<arr.length ; i++)
if (max == null || parseInt(arr[i][prop]) > parseInt(max[prop]))
max = arr[i];
return max;
用法如下:
var maxPpg = getMax(arr, "ppg");
console.log(maxPpg.player + " - " + maxPpg.team);
Fiddle demo
编辑
你也可以使用Javascript的"sort"方法获取前n个值:
function getTopN(arr, prop, n)
// clone before sorting, to preserve the original array
var clone = arr.slice(0);
// sort descending
clone.sort(function(x, y)
if (x[prop] == y[prop]) return 0;
else if (parseInt(x[prop]) < parseInt(y[prop])) return 1;
else return -1;
);
return clone.slice(0, n || 1);
用法:
var topScorers = getTopN(arr, "ppg", 2);
topScorers.forEach(function(item, index)
console.log("#" + (index+1) + ": " + item.player);
);
Fiddle demo
【讨论】:
这在我将数组作为 JavaScript 函数中的变量时有效,但当我将 arr 设为:var arr = $.getJSON(file);那么它就不起作用了。 @LesPaul 听起来像是异步问题?您必须使用回调,例如$.getJSON(function(arr) var top2 = getTopN(arr, "ppg", 2); );
为了将来参考,任何想要尝试将外部 JSON 文件加载到变量中的人都可以在这里查看:***.com/questions/2177548/load-json-into-variable
现在我已经更加关注控制台中的结果,我发现我没有得到我应该成为最佳射手的球员。例如,我应该得到凯文杜兰特(32.1),但我得到克里斯卡曼作为最佳得分手。如果 CK 是得分最低的人,我可以轻松解决这个问题,但他不是……他在中间。
@LesPaul 啊,我想我看到了问题所在。 JSON 中的值是字符串,因此它们被作为字符串进行比较。在值上使用parseInt
应该可以解决此问题。我已经在上面更新了。【参考方案2】:
我发现以下方法非常简洁:
arr.sort(
function(a, b)
return parseFloat(b['ppg']) - parseFloat(a['ppg']);
)[0]['player']
sn-p 中的演示:
var arr =[
"player" : "Andre Drummond",
"team" : "Detroit Pistons",
"ppg" : "15.4",
"rpg" : "11.6",
"apg" : "2.4",
"bpg" : "1.6",
"spg" : "0.8",
"3pg" : "0.1"
,
"player" : "Anthony Davis",
"team" : "New Orleans Pelicans",
"ppg" : "16.4",
"rpg" : "13.6",
"apg" : "2.6",
"bpg" : "3.5",
"spg" : "1.2",
"3pg" : "0.1"
,
"player" : "Carmelo Anthony",
"team" : "New York Knicks",
"ppg" : "27.4",
"rpg" : "5.4",
"apg" : "4.5",
"bpg" : "1.1",
"spg" : "1.5",
"3pg" : "1.6"
]
console.log(
arr.sort(
function(a, b)
return parseFloat(b['ppg']) - parseFloat(a['ppg']);
)[0]['player']
);
首先,我按降序对数组进行排序,然后选择包含最大值的第一个元素。在代码中,我找到了 player
具有最大 ppg
值的人。希望这会有所帮助!
【讨论】:
【参考方案3】:这应该可行:
var highestValue = 0; //keep track of highest value
//loop through array of objects
for (var i=0, len = ary.length; i<len; i++)
var value = Number(ary[i]["ppg"]);
if (value > highestValue)
highestValue = value;
【讨论】:
【参考方案4】:您可能会发现这个sortByAttribute
函数很有用。只需按您要对其进行排序的字符串传递属性,它就会返回具有您要查找的特定属性的最大值的任何对象。它仍然会返回整个数组,只是按您指定的属性升序排序。
var myArr = [
"player" : "Andre Drummond",
"team" : "Detroit Pistons",
"ppg" : "15.4",
"rpg" : "11.6",
"apg" : "2.4",
"bpg" : "1.6",
"spg" : "0.8",
"3pg" : "0.1"
,
"player" : "Anthony Davis",
"team" : "New Orleans Pelicans",
"ppg" : "16.4",
"rpg" : "13.6",
"apg" : "2.6",
"bpg" : "3.5",
"spg" : "1.2",
"3pg" : "0.1"
,
"player" : "Carmelo Anthony",
"team" : "New York Knicks",
"ppg" : "27.4",
"rpg" : "5.4",
"apg" : "4.5",
"bpg" : "1.1",
"spg" : "1.5",
"3pg" : "1.6"
]
function sortByAttribue(arr, attribute)
return arr.sort(function(a,b)
return a[attribute] < b[attribute];
);
sortByAttribue(myArr, "3pg") // returns Carmelo Anthony first
sortByAttribue(myArr, "bpg") // returns Anthony Davis first
【讨论】:
这几乎可以工作。无论第一个 sortByAttribute 函数返回什么,这都是我在 Firefox 和 Chrome 控制台中为 sortByAttributes 获得的值。因此,如果我将“3pg”作为第一个 sortByAttribute 函数中传递的值,那么对于两个 sortByAttribute 函数,我都会首先得到“Carmelo Anthony”。如果我将“bpg”作为第一个 sortByAttribute 函数中传递的值,我会首先为两个 sortByAttribute 函数获得“Anthony Davis”。【参考方案5】:function getMaxOfJson(jsonalreadyparsed, property)
var max = null;
for (var i=0 ; i<jsonalreadyparsed.length ; i++)
if(max == null)
max = jsonalreadyparsed[i][property];
else
if (parseFloat(jsonalreadyparsed[i][property]) > max)
max = jsonalreadyparsed[i][property];
return max;
这对我有用。
【讨论】:
【参考方案6】:正在寻找具有特定属性'x最大值的项目的函数:
function getMax(array, propName)
var max = 0;
var maxItem = null;
for(var i=0; i<array.length; i++)
var item = array[i];
if(item[propName] > max)
max = item[propName];
maxItem = item;
return maxItem;
用法:
$(document).ready(function()
$('#getMaxBtn').click(function()
var max = getMax(jsonArray, 'ppg');
alert(max.player);
);
);
【讨论】:
【参考方案7】:这将允许您选择您想要的统计数据以及您想要返回的信息。
http://jsbin.com/tudegofa/1/edit
data => 是数组
stat => 是您要排序的统计数据
info => 是您要返回的属性数组。
function getValues (data, stat, info)
var selectedValues = data.map(function(x)
return parseFloat(x[stat]);
)
var i = selectedValues.indexOf(Math.max.apply(Math, selectedValues));
var result = ;
info.forEach(function(x)
result[x] = test[i][x];
)
return result;
var myData = '';
$.getJSON('/url/to/grab/json', function(data)
myData = data;
);
getValues(myData, "bpg", ["player","team"]);
//[object Object]
// player: "Anthony Davis",
// team: "New Orleans Pelicans"
//
【讨论】:
我在 console.log 中得到这个错误:TypeError: data.map is not a function 你的数据是不是像你上面说的那样是数组的形式? 如上所列。需要注意的是它在一个外部的json文件中 我添加了一些代码来展示如何让你的 json 进入函数。【参考方案8】:从长远来看,简单感谢您。
function getMaxValueByAttribute(arr, attr)
var max = "-99999999999";
arr.forEach(function (member, index)
// console.log(member, index);
if (member.hasOwnProperty(attr) && parseFloat(member[attr]) > parseFloat(max))
max = member[attr];
// console.log("Max now: " + max);
);
return max;
然后像这样使用它:
var result = getMaxValueByAttribute(arr, "ppg");
// result = "27.4"
【讨论】:
【参考方案9】:您可以通过lodash轻松完成。
var players = [
"player": "Andre Drummond",
"team": "Detroit Pistons",
"ppg": "15.4",
"rpg": "11.6",
"apg": "2.4",
"bpg": "1.6",
"spg": "0.8",
"3pg": "0.1"
,
"player": "Anthony Davis",
"team": "New Orleans Pelicans",
"ppg": "16.4",
"rpg": "13.6",
"apg": "2.6",
"bpg": "3.5",
"spg": "1.2",
"3pg": "0.1"
,
"player": "Carmelo Anthony",
"team": "New York Knicks",
"ppg": "27.4",
"rpg": "5.4",
"apg": "4.5",
"bpg": "1.1",
"spg": "1.5",
"3pg": "1.6"
];
var topscorer = _
.chain(players)
.sortBy('ppg')
.reverse()
.map(function(o)
return 'Top scorer: ' + o.player + ' - ' + o.team;
)
.head()
.value();
console.log(topscorer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>
甚至更短:
var players = [
"player": "Andre Drummond",
"team": "Detroit Pistons",
"ppg": "15.4",
"rpg": "11.6",
"apg": "2.4",
"bpg": "1.6",
"spg": "0.8",
"3pg": "0.1"
,
"player": "Anthony Davis",
"team": "New Orleans Pelicans",
"ppg": "16.4",
"rpg": "13.6",
"apg": "2.6",
"bpg": "3.5",
"spg": "1.2",
"3pg": "0.1"
,
"player": "Carmelo Anthony",
"team": "New York Knicks",
"ppg": "27.4",
"rpg": "5.4",
"apg": "4.5",
"bpg": "1.1",
"spg": "1.5",
"3pg": "1.6"
];
console.log(_.maxBy(players, 'ppg').player);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
【讨论】:
【参考方案10】:我的解决方案在这里。请记住使用==
而不是===
来比较数字和字符串。
const getMax = (arr, prop) =>
const tmp = arr.map(x => x[prop]);
const max = Math.max(...tmp);
return arr.filter(x => x[prop] == max);
getMax(myArr,"bpg")
单行版本:
myArr.filter( x => x["bpg"] == Math.max(...myArr.map(x => x["bpg"])) )
【讨论】:
【参考方案11】:更简单:
const players =
[ player: 'Andre Drummond', team: 'Detroit Pistons', ppg: '15.4', rpg: '11.6', apg: '2.4', bpg: '1.6', spg: '0.8', '3pg': '0.1'
, player: 'Anthony Davis', team: 'New Orleans Pelicans', ppg: '16.4', rpg: '13.6', apg: '2.6', bpg: '3.5', spg: '1.2', '3pg': '0.1'
, player: 'Carmelo Anthony', team: 'New York Knicks', ppg: '27.4', rpg: '5.4', apg: '4.5', bpg: '1.1', spg: '1.5', '3pg': '1.6'
]
const getPlayerMax_on = cod => players.reduce((a,c)=>((+a[cod])<(+c[cod]))?c:a)
const maxOn_ppg = getPlayerMax_on('ppg')
console.log( maxOn_ppg.player, maxOn_ppg.team, maxOn_ppg.ppg )
【讨论】:
【参考方案12】:Lodash MaxBy
例如
var players = [
"name": "marvin",
"age": "21"
,
"name": "Lucy",
"age": "26"
,
"name": "james",
"age": "21"
];
maxBy(Players, 'age')
如果它是一个原始的 json 对象,即
maxBy(JSON.parse(Players), 'age')
=> "name": "Lucy","age": "26",
您甚至可以只返回年龄,即maxBy(Players, 'age').age
=> 26
【讨论】:
以上是关于获取 JSON 数组中的最大值的主要内容,如果未能解决你的问题,请参考以下文章