最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - group array by groups and sort by position - Stack Overflow

programmeradmin2浏览0评论

I have an array. I need to group this array by groups and sort by position. I tied to create a new array with group names as keys and values as sorted array grouped by group, but didn't work well. How can I do this?

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

I have an array. I need to group this array by groups and sort by position. I tied to create a new array with group names as keys and values as sorted array grouped by group, but didn't work well. How can I do this?

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];
    }
   }
}
Share Improve this question edited Jun 17, 2017 at 1:40 ekad 14.6k26 gold badges46 silver badges48 bronze badges asked Oct 16, 2015 at 21:49 Savo PušicaSavo Pušica 51 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Here's a simple straight forward answer:

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

When you want to do stuff like this though, it's usually remended to use a utility library like lodash or underscore.js, so that you don't have to "reinvent the wheel". Here's how it would look like using one of these libraries:

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

Here ya go!

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");

If you want to group objects, first think about what the resulting data would look like. Maybe something like this?

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

And so on. To transform a list into an object, consider using .reduce(). .reduce() takes a function as its first argument, and a resulting object as the second. The function iterates through each element of the array and reduces it into the given object.

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

Now all you need to do is use the built in sort to order the resulting arrays. You could do this by iterating through the keys of the resulting object and applying .sort() to each array. .sort() takes a function as an argument which accesses the data and provides a parison function.

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

And you would implement it like so

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

评论列表(0)

  1. 暂无评论