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

javascript - Sort an array of objects if property exists - Stack Overflow

programmeradmin0浏览0评论

I have an array of objects. Out of each of these objects onle few of them have a property and I want to sort the array putting those objects at top which have that property.

Ex -

arr= [{key1: "obj1val1", key2 :"obj1val2"}, 
      {key2 :"obj2val2"}, 
      {key1: "obj3val3", key2 :"obj3val3"},
      {key2 :"obj4val1"},
      {key1: "obj5val1", key2 :"obj5val2"}
]

Sorted by key1

Expected Result - [{key1: "obj1val1", key2 :"obj1val2"}, 
                   {key1: "obj3val3", key2 :"obj3val3"},
                   {key1: "obj5val1", key2 :"obj5val2"}, 
                   {key2 :"obj2val2"}, 
                   {key2 :"obj4val1"}]

I have tried below approach-

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

Not exactly but I see discrepancy from the above approach. For a array bigger length, some of the objects which have key1 are not moved to top. Can this be done by internal sort method of javascript? If yes, how will the custom function compare ?

Can only support ES5 methods.

I have an array of objects. Out of each of these objects onle few of them have a property and I want to sort the array putting those objects at top which have that property.

Ex -

arr= [{key1: "obj1val1", key2 :"obj1val2"}, 
      {key2 :"obj2val2"}, 
      {key1: "obj3val3", key2 :"obj3val3"},
      {key2 :"obj4val1"},
      {key1: "obj5val1", key2 :"obj5val2"}
]

Sorted by key1

Expected Result - [{key1: "obj1val1", key2 :"obj1val2"}, 
                   {key1: "obj3val3", key2 :"obj3val3"},
                   {key1: "obj5val1", key2 :"obj5val2"}, 
                   {key2 :"obj2val2"}, 
                   {key2 :"obj4val1"}]

I have tried below approach-

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

Not exactly but I see discrepancy from the above approach. For a array bigger length, some of the objects which have key1 are not moved to top. Can this be done by internal sort method of javascript? If yes, how will the custom function compare ?

Can only support ES5 methods.

Share Improve this question edited Sep 22, 2018 at 21:46 David Thomas 253k53 gold badges381 silver badges418 bronze badges asked Sep 22, 2018 at 21:35 RahulBRahulB 2,1101 gold badge20 silver badges27 bronze badges 5
  • 2 Don't use splice while you are iterating. – Bergi Commented Sep 22, 2018 at 21:39
  • Do you actually want to sort them by comparing all of them with each other, or do you want to keep the order but move those with the property to the top? In the latter case, don't use sort. – Bergi Commented Sep 22, 2018 at 21:40
  • @Bergi That is why I have copied the original array and spliced the copied array. I want to keep the order but move the property to top – RahulB Commented Sep 22, 2018 at 21:41
  • Still, the indices of the other elements change when you splice out one element. – Bergi Commented Sep 22, 2018 at 21:43
  • 1 Just use var withProp = [], withoutProp = []; … if ("key1" in arr[i]) withProp.push(arr[i]); else withoutProp.push(arr[i]); …. Don't copy anything beforehand or try to splice from it during a loop. – Bergi Commented Sep 22, 2018 at 21:44
Add a comment  | 

4 Answers 4

Reset to default 15

Can this be done by internal sort method of javascript

Yes: Simply prefer the entry that has the property:

arr.sort(function(left, right) {
    return left.hasOwnProperty("key1") ? -1 : right.hasOwnProperty("key1") ? 1 : 0
});

Live Example:

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

If you also want to sort by that property's value:

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

Live Example:

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

Here is a working snippet that gives your requested result and is easily extended. It uses the native array 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)

A kind of janky way you can do it is:

arr.filter(obj => obj.hasOwnProperty('key1')).concat(arr.filter(obj => !obj.hasOwnProperty('key1')));

https://github.com/arraybrain/arraybrain

for complex array stuff, you can use it

发布评论

评论列表(0)

  1. 暂无评论