代码之家  ›  专栏  ›  技术社区  ›  Si8

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

  •  0
  • Si8  · 技术社区  · 6 年前

    我的问题在代码注释中:

    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 )

    0 回复  |  直到 6 年前
        1
  •  1
  •   Nina Scholz    6 年前

    你可以找到 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; }