我有一个数组:
arr =
[{"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]}]
arr
由6个元素组成。这六个元素中的每一个都由另一个数组keys
组成。我需要按照每个中键的数量的升序重新排列六个元素。这意味着我需要以这种方式重新排列数组:
arr =
[
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]},
{"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
]
我试图获取每个数组元素的keys
内的元素数量,如下面的代码所示:
var arrMap = [];
arr.forEach(function(array_) {
key_ = array_.keys;
var count = 0;
key_.forEach(function(arrKey) {
count++;
var keyCode = arrKey.sid;
})
arrMap.push({'nid':array_.nid, 'count': count});
})
console.log(arrMap);
这给了我以下输出:
[{"nid":"MIA","count":2},{"nid":"MID","count":1},{"nid":"MIT","count":10},{"nid":"MIO","count":3},{"nid":"MIS","count":2},{"nid":"MIH","count":1}]
现在我对如何使用count
关键元素重新排列数组感到困惑。任何指导/帮助都将受到高度赞赏!
答案 0 :(得分:3)
您可以尝试.sort
let arr = [ {"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]} ];
arr.sort((a, b) => a.keys.length - b.keys.length);
console.log(arr);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
答案 1 :(得分:0)
您可以使用数组
的排序功能来实现此目的arr.sort(function(a,b){return a.keys.length - b.keys.length})