按组分组和按位置排序

时间:2015-10-16 21:49:42

标签: javascript arrays position grouping

我有一个数组。我需要按组对这个数组进行分组并按位置排序。我绑定创建一个新的数组,组名作为键,值作为按组分组的排序数组,但不能很好地工作。我怎么能这样做?

a = [
    {id:1,name:'qw'group:'C',name:'hite',position:'1'},
    {id:2,name:'qwe'group:'B',name:'ite',position:'2'},
    {id:3,name:'qwer'group:'A',name:'ite',position:'3'},
    {id:4,name:'qer'group:'D',name:'te',position:'4'},
    {id:5,name:'wer'group:'C',name:'whit',position:'5'},
    {id:6,name:'er'group:'B',name:'whi',position:'6'},
]

function groupDo(array){                
  var groups = [];
  for (var i in array){
    groups[array[i].group] = array[i].group;
  }
  for (var i in array){
    if (groups[array[i].group] == array[i].group){
      groups[array[i].group] = array[i];
    }
   }
}

3 个答案:

答案 0 :(得分:1)

这是一个简单的直接答案:

var sortByPosition = function(obj1, obj2) {
  return obj1.position - obj2.position;
};

var arr = [
  { id: 1, name: 'qw', group: 'C', name: 'hite', position: '1' },
  { id: 2, name: 'qwe', group: 'B', name: 'ite', position: '2' },
  { id: 3, name: 'qwer', group: 'A', name: 'ite', position: '3' },
  { id: 4, name: 'qer', group: 'D', name: 'te', position: '4' },
  { id: 5, name: 'wer', group: 'C', name: 'whit', position: '5' },
  { id: 6, name: 'er', group: 'B', name: 'whi', position: '6' },
];

var grouped = {};

for (var i = 0; i < arr.length; i += 1) {
  if(!grouped[arr[i].group]) {
    grouped[arr[i].group] = [];
  }
  grouped[arr[i].group].push(arr[i]);
}

for (var group in grouped) {
  grouped[group] = grouped[group].sort(sortByPosition);
}

console.log(grouped);

当你想做这样的事情时,通常建议使用像lodashunderscore.js这样的实用程序库,这样你就不必“重新发明轮子”了。以下是使用其中一个库的方式:

var arr = [
  { id: 1, name: 'qw', group: 'C', name: 'hite', position: '1' },
  { id: 2, name: 'qwe', group: 'B', name: 'ite', position: '2' },
  { id: 3, name: 'qwer', group: 'A', name: 'ite', position: '3' },
  { id: 4, name: 'qer', group: 'D', name: 'te', position: '4' },
  { id: 5, name: 'wer', group: 'C', name: 'whit', position: '5' },
  { id: 6, name: 'er', group: 'B', name: 'whi', position: '6' },
];

var grouped = _.groupBy(arr, 'group');

for (var group in grouped) {
  _.sortBy(grouped[group], 'position');
}

console.log(grouped);

答案 1 :(得分:1)

这里你去!

a = [
    {id:1,name:'qw',group:'C',name:'hite',position:'1'},
    {id:2,name:'qwe',group:'B',name:'ite',position:'2'},
    {id:3,name:'qwer',group:'A',name:'ite',position:'3'},
    {id:4,name:'qer',group:'D',name:'te',position:'4'},
    {id:5,name:'wer',group:'C',name:'whit',position:'5'},
    {id:6,name:'er',group:'B',name:'whi',position:'6'},
]

function groupAndSort(array, groupField, sortField) {
    var groups = {}; // This object will end being keyed by groups, and elements will be arrays of the rows within the given array, which have been sorted by the sortField
    // Put all the rows into groups
    for (var i = 0; i < array.length; i++) {
        var row = array[i];
        var groupValue = row[groupField];
        groups[groupValue] = groups[groupValue] || [];
        groups[groupValue].push(row);
    }
    // Sort each group
    for (var groupValue in groups) {
        groups[groupValue] = groups[groupValue].sort(function(a, b) {
            return a[sortField] - b[sortField];
        });
    }
    // Return the results
    return groups;
}

var groupedAndSorted = groupAndSort(a, "group", "position");

答案 2 :(得分:0)

如果要对对象进行分组,请首先考虑结果数据的外观。也许是这样的?

var grouped = {
    A : [
         {id:3,name:'qwer', group:'A',name:'ite',position:'3'}
    ],
    B : [],
    C : [],
    D : []
};

等等。要将列表转换为对象,请考虑使用.reduce()。 .reduce()将函数作为其第一个参数,将结果对象作为第二个参数。该函数遍历数组的每个元素并将其缩减为给定的对象。

var data = [
  {id:1,name:'qw', group:'C',name:'hite',position:'1'},
  {id:2,name:'qwe', group:'B',name:'ite',position:'2'},
  {id:3,name:'qwer', group:'A',name:'ite',position:'3'},
  {id:4,name:'qer', group:'D',name:'te',position:'4'},
  {id:5,name:'wer', group:'C',name:'whit',position:'5'},
  {id:6,name:'er', group:'B',name:'whi',position:'6'},
]


// acc is the accumulated object, x is each element of the array
data.reduce(function(acc, x) {
    // first check if the given group is in the object
    acc[x.group] = acc[x.group] ?  acc[x.group].concat(x) : [x];

    return acc;

}, {});  // this is the resulting object

现在您需要做的就是使用内置排序来对结果数组进行排序。您可以通过迭代生成的对象的键并将.sort()应用于每个数组来完成此操作。 .sort()接受一个函数作为参数来访问数据并提供比较函数。

// a and b are elements of the array
array.sort(function(a, b) {
  if (a.position > b.position) {
      return -1;
  } else if (b.position > a.position) {
      return 1;
  } else {
      return 0;
  }
});

你会像这样实现它

var result = Object.keys(data).map(function(d){
    return d.sort(f); // f is the function above
});