我有一个对象数组。在每个这些对象中,只有几个具有属性,我想对数组进行排序,将具有该属性的那些对象放在顶部。
Ex-
arr= [{key1: "obj1val1", key2 :"obj1val2"},
{key2 :"obj2val2"},
{key1: "obj3val3", key2 :"obj3val3"},
{key2 :"obj4val1"},
{key1: "obj5val1", key2 :"obj5val2"}
]
按key1排序
Expected Result - [{key1: "obj1val1", key2 :"obj1val2"},
{key1: "obj3val3", key2 :"obj3val3"},
{key1: "obj5val1", key2 :"obj5val2"},
{key2 :"obj2val2"},
{key2 :"obj4val1"}]
我尝试了以下方法-
sort : function(arr) {
var copyArr = arr.slice();
var newArr = [];
for(var i=0; i<arr.length; i++){
if(arr[i].key1){
newArr.push(arr[i]);
copyArr.splice(i, 1);
}
}
Array.prototype.push.apply(newArr, copyArr);
return newArr;
}
不太准确,但是我发现上述方法存在差异。对于更大长度的数组,某些具有key1的对象不会移到顶部。
可以通过JavaScript的内部sort
方法来完成此操作吗?如果是,自定义函数将如何比较?
仅支持ES5方法。
答案 0 :(得分:4)
这可以通过javascript的内部排序方法完成吗
是:只需选择具有以下属性的条目:
arr.sort(function(left, right) {
return left.hasOwnProperty("key1") ? -1 : right.hasOwnProperty("key1") ? 1 : 0
});
实时示例:
var arr = [
{key1: "obj1val1", key2 :"obj1val2"},
{key2 :"obj2val2"},
{key1: "obj3val3", key2 :"obj3val3"},
{key2 :"obj4val1"},
{key1: "obj5val1", key2 :"obj5val2"}
];
arr.sort(function(left, right) {
return left.hasOwnProperty("key1") ? -1 : right.hasOwnProperty("key1") ? 1 : 0
});
console.log(arr);
如果您还想按该属性的值排序:
arr.sort(function(left, right) {
var leftHas = left.hasOwnProperty("key1");
var rightHas = right.hasOwnProperty("key1");
if (leftHas && rightHas) {
return left.key1.localeCompare(right.key1);
}
return leftHas ? -1 : rightHas ? 1 : 0;
});
实时示例:
var arr = [
{key1: "obj1val1", key2 :"obj1val2"},
{key2 :"obj2val2"},
{key1: "obj3val3", key2 :"obj3val3"},
{key2 :"obj4val1"},
{key1: "obj5val1", key2 :"obj5val2"}
];
arr.sort(function(left, right) {
var leftHas = left.hasOwnProperty("key1");
var rightHas = right.hasOwnProperty("key1");
if (leftHas && rightHas) {
return left.key1.localeCompare(right.key1);
}
return leftHas ? -1 : rightHas ? 1 : 0;
});
console.log(arr);
答案 1 :(得分:0)
您可以采用的一种变态方法:
arr.filter(obj => obj.hasOwnProperty('key1')).concat(arr.filter(obj => !obj.hasOwnProperty('key1')));
答案 2 :(得分:0)
这是一个工作片段,可以提供您所需的结果,并且可以轻松扩展。它使用本机数组sort
。
arr = [{
key1: "obj1val1",
key2: "obj1val2"
},
{
key2: "obj2val2"
},
{
key1: "obj3val3",
key2: "obj3val3"
},
{
key2: "obj4val1"
},
{
key1: "obj5val1",
key2: "obj5val2"
}
]
const sorted = arr.sort((a, b) => {
const k1 = a.key1 === undefined ? 0 : 1
const k2 = b.key1 === undefined ? 0 : 2
return k2- k1
})
console.log(sorted)
答案 3 :(得分:0)
https://github.com/arraybrain/arraybrain
对于复杂数组的东西,您可以使用它