对数组键值的对象的数组进行排序

时间:2018-12-13 03:20:12

标签: javascript angular typescript

我正在尝试在打字稿中为nvd3图表的array对象数组排序,但没有运气,对此表示感谢,

数据看起来像这样

[
 {"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"}]}
]

输出应为以下内容,

[
 {"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"}]}
]

我试图做这样的事没有运气,

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));

对此表示任何帮助

3 个答案:

答案 0 :(得分:0)

您要对数组中的“ val”键进行正确排序吗?这就是您要做的。

arr.map( (element) => element.val.sort(
   (a,b) => (a.s > b.s) ? 1 : ((b.s > a.s) ? -1 : 0)) 
);

答案 1 :(得分:0)

您可以同时使用reducesort

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) => a.s- b.s)});
  return prev.concat(item);

},[])

console.log({output});

答案 2 :(得分:0)

您应该使用forEach,因为它不会返回类似mapreduce的结果,从而有效地将数组重新放置在适当的位置。

解决方案

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) => a.s - b.s);
})

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/map#Return_value

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Return_value