Как переставить ключ объекта в начало сгруппированного объекта - PullRequest
0 голосов
/ 14 февраля 2019

Мой вопрос в комментариях к коду:

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

( скрипка )

1 Ответ

0 голосов
/ 14 февраля 2019

Вы можете найти количество заданных 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; }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...