我的问题在代码注释中:
var myObj = [
{
0: 'company1',
1: { count: 3 }
},
{
0: 'company2',
1: { count: 3 }
},
{
0: 'company3',
1: { count: 2 }
},
{
0: 'company1',
1: { count: 1 }
},
];
var companytoshift = 'company2';
var f = [];
for (var i = 0; i < myObj.length; i++) {
f.push(myObj[i][1].count);
}
var isMultipleSameValues = samevaluemultiplecompany(f);
if (isMultipleSameValues) { //we have multiple company with same value
/*
if 'companytoshift' exist in the object array
if 'companytoshift' has a count value that is same with other companies
then shift that company to the top of the same count value group.
For the example object above, after we perform the function, it would be this:
var obj = [
{
0: 'company2',
1: {
count: 3
}
},
{
0: 'company1',
1: {
count: 3
}
},
{
0: 'company3',
1: {
count: 2
}
},
{
0: 'company1',
1: {
count: 1
}
},
];
*/
/* as you can see company2 moved above company1 because it had the same count value as another company, which is 3, and also because it was the company in the `companytoshift` variable
*/
}
function samevaluemultiplecompany(a) {
var counts = [];
for (var i = 0; i <= a.length; i++) {
if (counts[a[i]] === undefined) {
counts[a[i]] = 1;
} else {
return true;
}
}
return false;
}
( fiddle )
最佳答案
您可以找到给定 company
的计数,然后先按 company
排序,然后再按计数排序。通过稳定排序,数组末尾的其他元素未排序。
function sort(array, company) {
var count = array.find(([c]) => c === company)[1].count;
return array.some((c => ({ 1: { count: v } }) => v === count && ++c === 2)(0))
? array.sort((a, b) =>
(b[0] === company) - (a[0] === company) ||
(b[1].count === count) - (a[1].count === count)
)
: array;
}
var array = [
["company1", { count: 3 }],
["company3", { count: 1 }],
["company2", { count: 3 }],
["company4", { count: 0 }],
["company5", { count: 0 }]
];
console.log(sort(array, "company2"));
console.log(sort(array, "company3"));
console.log(sort(array, "company5"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何将对象键重新排列到分组对象的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54694128/