如何将对象键重新排列到分组对象的开头

时间:2019-02-14 15:42:27

标签: javascript object

我的问题在代码注释中:

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

1 个答案:

答案 0 :(得分:1)

您可以找到给定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; }