我需要根据另一个数组对数组进行排序。但是,有一个更大的数组,但我只想对某些项属性进行排序。第一个数组如下所示:
var data = [ { id : "23", name : "Item 1", isActive : true},
{ id : "25", name : "Item 2", isActive : false},
{ id : "26", name : "Item 3", isActive : false},
{ id : "30", name : "Item 4", isActive : true},
{ id : "45", name : "Item 5", isActive : true}
]
然后我这样做以获取活动项目的ID:
var ids = _.filter(c, function(el) {
return el.isActive === true;
}).map(function(e) { return e.id;}) //["23","30","45"]
我做了一些操作(数据库比较),我得到了这样的结果:
var sorted = ["45","23","30"]
当我第一次按isActive对项目进行排序时,我只想对活动的项目进行排序。 (取决于上面排序的数组)像这样:
var expected = [
{ id : "45", name : "Item 5", isActive : true},
{ id : "23", name : "Item 1", isActive : true},
{ id : "30", name : "Item 4", isActive : true},
//try to keep order for the last values
{ id : "25", name : "Item 2", isActive : false},
{ id : "26", name : "Item 3", isActive : false}]
我尝试使用_.sortBy方法,但这没有按预期工作:
var sortObj = sorted.reduce(function(acc, value, index) {
acc[value] = value;
return acc;
}, {});
sortedItems = _.sortBy(data, function(x) {
return _.indexOf(sortObj, x.id)
});
但它没有按预期工作
有什么想法吗?非常感谢提前=)
答案 0 :(得分:0)
您可以运行2个过滤器并将结果合并到一个数组中。 return el.isActive === true;并返回el.isActive === false; 您可以在插入最终数组
之前对两个结果进行排序答案 1 :(得分:0)
您可以使用map和sort对象进行排序。
var data = [{ id: "23", name: "Item 1", isActive: true }, { id: "25", name: "Item 2", isActive: false }, { id: "26", name: "Item 3", isActive: false }, { id: "30", name: "Item 4", isActive: true }, { id: "45", name: "Item 5", isActive: true }],
sorted = ["45", "23", "30"],
order = {};
sorted.forEach(function (a, i) { order[a] = i + 1; });
// temporary array holds objects with position and sort-value
var mapped = data.map(function (el, i) {
return { index: i, active: el.isActive, value: order[el.id] || i };
});
// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
return b.active - a.active || a.value - b.value;
});
// container for the resulting order
var result = mapped.map(function (el) {
return data[el.index];
});
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)
由于您希望保留已排序和无效的订单。 我们可以使用两个关联的数组来保存订单的索引,然后可以使用两个关联的数组来创建一种复合索引。
更新:希望简化并简化操作。
var data = [ { id : "23", name : "Item 1", isActive : true},
{ id : "25", name : "Item 2", isActive : false},
{ id : "26", name : "Item 3", isActive : false},
{ id : "30", name : "Item 4", isActive : true},
{ id : "45", name : "Item 5", isActive : true}
];
var sorted = ["45","23","30"];
//true = active sort, false = data sort
var order = { true: {}, false: {}};
//create order index for data
data.forEach(function (o, i) { order[false][o.id] = i; });
//create order index for sort
sorted.forEach(function (v, i) { order[true][v] = i });
data.sort(function (a, b) {
return (b.isActive - a.isActive) ||
order[a.isActive][a.id] - order[b.isActive][b.id];
});
console.log(data);