我有一个Javascript列表
var list = [
{ date: "2005-04-01", position: 12, worker: "John", prop: "k11" },
{ date: "2006-02-01", position: 72, worker: "John", prop: "k12" },
{ date: "2005-09-06", position: 42, worker: "Aleks", prop: "k43" },
{ date: "2004-07-02", position: 12, worker: "Mark", prop: "k12" },
];
我想创建一个类似list.sort('position','12')的排序函数,它将按位置字段的值'12'对列表进行排序并给出输出。
日期:“2005-04-01”,职位:12,工人:“约翰”,道具:“k11”
日期:“2004-07-02”,职位:12,工人:“马克”,道具:“k12”
日期:“2006-02-01”,职位:72,工人:“John”,道具:“k12”
日期:“2005-09-06”,职位:42,工人:“Aleks”,道具:“k43”
但你也可以把它称为list.sort('worker','John'),它也会在工人排序之后按日期排序
答案 0 :(得分:2)
如果新引用正常,找到所有匹配项,找到所有不匹配项,连接这两个数组
function bringToTop(arrOfObj, prop, val) {
return arrOfObj.filter(e => e[prop] === val).concat(
arrOfObj.filter(e => e[prop] !== val)
);
}
e.g。
var arr = [
{foo: 0, bar: 0, baz: 'fizz'},
{foo: 0, bar: 1, baz: 'buzz'},
{foo: 1, bar: 0, baz: 'fizz'},
{foo: 1, bar: 1, baz: 'buzz'}
];
bringToTop(arr, 'baz', 'buzz');
/*
[
{foo: 0, bar: 1, baz: 'buzz'},
{foo: 1, bar: 1, baz: 'buzz'},
{foo: 0, bar: 0, baz: 'fizz'},
{foo: 1, bar: 0, baz: 'fizz'}
]
*/
如果你想要相同的参考,取这个结果,清空原件,然后按结果
var res = bringToTop(arr, 'baz', 'buzz');
arr.length = 0;
Array.prototype.push.apply(arr, res);
答案 1 :(得分:1)
这是一个对给定键/值对进行特权排序的提案。
特点:
var list = [
{ date: "2005-04-01", position: 12, worker: "John", prop: "k11" },
{ date: "2006-02-01", position: 72, worker: "John", prop: "k12" },
{ date: "2005-09-06", position: 42, worker: "Aleks", prop: "k43" },
{ date: "2004-07-02", position: 12, worker: "Mark", prop: "k12" },
];
function setCondition(condition) {
var key = Object.keys(condition)[0],
value = condition[key];
return function (a, b) {
function x(o) { return -(o[key] === value); }
return x(a) - x(b) || b.date.localeCompare(a.date);
}
}
document.write('<pre>' + JSON.stringify(list.sort(setCondition({ position: 12 })), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(list.sort(setCondition({ worker: 'John' })), 0, 4) + '</pre>');
&#13;