[英]sort array of object of array key value
I'm trying to sort an array of objects of array for nvd3 chart in typescript with no luck, any help on this is appreciated, 我正在尝试在打字稿中为nvd3图表的array对象数组排序,但没有运气,对此的任何帮助都值得赞赏,
the data looks something like this, 数据看起来像这样,
[
{"k": "Name1", "val": [{"s": 33, "d": "sa"}, {"s": 1, "d": "as"}, {"s": 56, "d": "te"}]}
{"k": "Name2", "val": [{"s": 31, "d": "re"}, {"s": 4, "d": "sa"}, {"s": 1, "d": "ba"}]}
]
The output should be something below, 输出应为以下内容,
[
{"k": "Name1", "val": [{"s": 1, "d": "as"}, {"s": 33, "d": "sa"}, {"s": 56, "d": "te"}]}
{"k": "Name2", "val": [{"s": 1, "d": "ba"}, {"s": 4, "d": "sa"}, {"s": 31, "d": "re"}]}
]
I tried doing something like this with no luck, 我尝试做这样的事没有运气,
arr=[
{"k": "Name1", "val": [{"s": 33, "d": "sa"}, {"s": 1, "d": "as"}, {"s": 56, "d": "te"}]}
{"k": "Name2", "val": [{"s": 31, "d": "re"}, {"s": 4, "d": "sa"}, {"s": 1, "d": "ba"}]}
]
arr.sort((a,b) => (a.s > b.s) ? 1 : ((b.s > a.s) ? -1 : 0));
any help on this is really appreciated 对此的任何帮助都非常感谢
You want the "val" key in the array be sorted right?. 您想对数组中的“ val”键进行排序吗? So this is what you have to do it.
这就是您要做的。
arr.map( (element) => element.val.sort(
(a,b) => (a.s > b.s) ? 1 : ((b.s > a.s) ? -1 : 0))
);
you can achieve this by using reduce
and sort together 您可以通过使用
reduce
和sorting来实现
const input = [ {"k": "Name1", "val": [{"s": 33, "d": "sa"}, {"s": 1, "d": "as"}, {"s": 56, "d": "te"}]}, {"k": "Name2", "val": [{"s": 31, "d": "re"}, {"s": 4, "d": "sa"}, {"s": 1, "d": "ba"}]} ]; const output = input.reduce( (prev, element) => { const item = element; Object.assign({}, item, {val: element.val.sort((a,b) => as- bs)}); return prev.concat(item); },[]) console.log({output});
You should use forEach
as it doesn't return a result like map
and reduce
, effectively resorting your array in place. 您应该使用
forEach
因为它不会返回诸如map
和reduce
的结果, reduce
有效地将数组重新放置在适当的位置。
const data = [ {"k": "Name1", "val": [{"s": 33, "d": "sa"}, {"s": 1, "d": "as"}, {"s": 56, "d": "te"}]}, {"k": "Name2", "val": [{"s": 31, "d": "re"}, {"s": 4, "d": "sa"}, {"s": 1, "d": "ba"}]} ] data.forEach(obj => { obj.val.sort((a, b) => as - bs); }) console.log(data)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Return_value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Return_value
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Return_value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Return_value
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Return_value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Return_value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.