在javascript中基于另一个数组对数组进行排序,同时在最后保留未排序的元素

时间:2016-09-30 09:34:07

标签: javascript arrays sorting

我有一个数组,我想根据另一个数组进行排序。如果两个数组的长度相同,则下面的代码可以正常工作。但是,如果我的数组order缺少一个元素,我仍然希望在新的排序数组的末尾显示它。这是一个简单的例子:

//Source arrays
var order = [{_id: '123', type: '2'},{_id: '123', type: '1'}];
var elements = [{_id: '124', type: '1', name: '(should be last, not sorted)'},{_id: '123', type: '1', name: 'second(should be second)'},{_id: '123', type: '2', name: 'third(should be first)'}];

var sorted = [];
for (var i = 0, len = order.length; i < len; i++) {
    var element = elements.filter(function (el) {
		return el.type == order[i]['type'] &&
               el._id == order[i]['_id'];
    });
    sorted.push(element[0]);
}

//Just for testing
var list = document.createElement('ul');
for (var i = 0, len = sorted.length; i < len; i++) {
      var item = document.createElement('li');
      item.appendChild(document.createTextNode(sorted[i]['name']));
      list.appendChild(item);
}
document.getElementById('list').appendChild(list);
<div id="list"></div>

如您所见,现在我的排序数组中只有两个项目。如何在最后添加elements中缺少的项目?

3 个答案:

答案 0 :(得分:1)

您可以使用array.findIndex获取索引,然后进行相应排序

var order = [{_id: '123', type: '2'},{_id: '123', type: '1'}];
var elements = [{_id: '124', type: '1', name: '(should be last, not sorted)'},{_id: '123', type: '1', name: 'second(should be second)'},{_id: '123', type: '2', name: 'third(should be first)'}];


elements.sort(function(a, b) {
  var MAX_VALUE = 9999999;
  var index_a = order.findIndex(function(el) {
    return el._id === a._id && el.type === a.type;
  });
  var index_b = order.findIndex(function(el) {
    return el._id === b._id && el.type === b.type;
  });
  
  index_a = index_a < 0? MAX_VALUE : index_a;
  index_b = index_b < 0? MAX_VALUE : index_b;

  return index_a > index_b ? 1 : index_a < index_b ? -1 : 0
});

console.log(elements)

答案 1 :(得分:1)

您可以使用Array#sort和对象作为排序顺序。如果没有给出订单,则元素将移动到最后。

&#13;
&#13;
const indexOfListToUpdate = obj.get('elem').findIndex(listItem => {
  return listItem.get('name') === 'third';
});
obj = obj.setIn(['elem', indexOfListingToUpdate, 'count'], 4);
&#13;
function sortWithOrder(array) {
    function getOrder(o) { return (orderObj[o._id] || {})[o.type] || Infinity; }

    var orderObj = Object.create(null);
    array.forEach(function (a, i) {
        orderObj[a._id] = orderObj[a._id] || {};
        orderObj[a._id][a.type] = i + 1;
    });
    return function (a, b) {
        return getOrder(a) - getOrder(b);
    };
}

var order = [{ _id: '123', type: '2' }, { _id: '123', type: '1' }],
    elements = [{ _id: '124', type: '1', name: '(should be last, not sorted)' }, { _id: '123', type: '1', name: 'second(should be second)' }, { _id: '123', type: '2', name: 'third(should be first)' }];

elements.sort(sortWithOrder(order));
console.log(elements);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

var sorted = elements.sort((a, b) => 
               (order.findIndex(i => a._id === i._id && a.type === i.type) + 1 || order.length + 1) 
             - (order.findIndex(i => b._id === i._id && b.type === i.type) + 1 || order.length + 1)
             );

'use strict';

var order = [{
  _id: '123',
  type: '2'
}, {
  _id: '123',
  type: '1'
}];
var elements = [{
  _id: '124',
  type: '1',
  name: '(should be last, not sorted)'
}, {
  _id: '123',
  type: '2',
  name: 'third(should be first)'
}, {
  _id: '124',
  type: '1',
  name: '(should be last, not sorted)'
}, {
  _id: '123',
  type: '1',
  name: 'second(should be second)'
}, {
  _id: '123',
  type: '1',
  name: 'second(should be second)'
}, {
  _id: '123',
  type: '2',
  name: 'third(should be first)'
}, {
  _id: '123',
  type: '2',
  name: 'third(should be first)'
}, {
  _id: '123',
  type: '1',
  name: 'second(should be second)'
}, {
  _id: '124',
  type: '1',
  name: '(should be last, not sorted)'
}];

var sorted = elements.sort(function (a, b) {
  return (order.findIndex(function (i) {
    return a._id === i._id && a.type === i.type;
  }) + 1 || order.length + 1) - (order.findIndex(function (i) {
    return b._id === i._id && b.type === i.type;
  }) + 1 || order.length + 1);
});

//Just for testing
var list = document.createElement('ul');
for (var i = 0, len = sorted.length; i < len; i++) {
      var item = document.createElement('li');
      item.appendChild(document.createTextNode(sorted[i]['name']));
      list.appendChild(item);
}
document.getElementById('list').appendChild(list);
<div id="list"></div>