如何根据数组字段值javascript对数组进行排序

时间:2021-08-27 15:14:04

I have the following array:

我有以下数组:

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

I want to sort the array so it returns a new array by 'presence': 'online' users displaying first before offline items.

我想对数组进行排序,让它根据“存在”返回一个新的数组:“在线”用户在脱机项之前先显示。

So if sorted, it should return something like this:

如果排序,它应该返回这样的东西:

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online' },
    { id: '7XHSK', name: 'rene', presence: 'online' },
    { id: '8YSHJ',    name: 'mary', presence: 'offline' }
];

Something like this:

是这样的:

const newArray = objs.sort((a, b) => {
      if (a.presence === 'online') {
        return 1;
      } else if (b.presence === 'offline') {
        return -1;
      } else {
        return 0;
      }
    })

return newArray;
}

What is the right way to get the expected result?

得到预期结果的正确方法是什么?

10 个解决方案

#1


6  

You can use localeCompare method.

您可以使用localeCompare方法。

var objs = [ { id: 'X82ns', name: 'james', presence: 'online' }, { id: '8YSHJ', name: 'mary', presence: 'offline' }, { id: '7XHSK', name: 'rene', presence: 'online' } ];

objs.sort((a,b) => b.presence.localeCompare(a.presence));
console.log(objs);

Don't forget that the sort() method sorts the elements of an array in place so you do not need to use const newArray = objs.sort....

别忘了sort()方法排序数组的元素,所以您不需要使用const newArray = objs.sort ....

#2


1  

Use sort function with condition of a.presence < b.presence because of online is bigger than offline (f and n)

使用具有a条件的排序函数。< b。线上的存在大于线下的存在(f和n)

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

objs.sort(function(a, b) {
  return a.presence < b.presence;
});

console.log(objs);

#3


1  

You could simply compare the String with >, = and <

可以将字符串与> =和 <进行比较< p>

let objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

let res = objs.sort((a,b) => a.presence > b.presence ? -1 : a.presence == b.presence ? 0 : 1);
console.log(res);

#4


1  

let objArr = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

let onlineArr = objArr.filter(x=>x.presence === 'online')
let offlineArr = objArr.filter(x=>x.presence === 'offline')
console.log([...onlineArr, ...offlineArr])

In terms of readability, you can split them into two array and using array destructuring to join them at last

在可读性方面,您可以将它们分割为两个数组,最后使用数组析构来连接它们

#5


1  

You could take an object with the order as values and sort by it. This allowes to use a default value for unknow values.

你可以取一个具有顺序的对象作为值并对其进行排序。这允许对未知值使用默认值。

var array = [{ id: 'X82ns', name: 'james', presence: 'online' }, { id: '8YSHJ', name: 'mary', presence: 'offline' }, { id: '7XHSK', name: 'rene', presence: 'online' }],
    order = { online: 1, offline: 2, default: Infinity };
    
array.sort((a, b) => (order[a.presence] || order.default) - (order[b.presence] || order.default));

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

#6


1  

Use the > sign to get online first and offline at the end. You can also create a separate function sortFn so this logic can be reused for multiple arrays.

使用>标志,首先在线,最后离线。您还可以创建一个单独的函数sortFn,以便可以为多个数组重用该逻辑。

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

function sortFn(a, b){
  return b.presence > a.presence;
}
objs.sort(sortFn);
console.log(objs);

#7


1  

You need to actually compare the items, and if they are now the same, then check for presence

您需要实际地比较这些项目,如果它们现在是相同的,那么检查是否存在

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

const newArray = objs.sort((a, b) => {
      if (a.presence !== b.presence) {
        return a.presence === "online" ? -1 : 1;
      }
      return 0;
});


console.log(newArray);

#8


1  

Try this:

试试这个:

const newArray = objs.sort((a, b) => {
      if (a.presence === 'online' && b.presence === 'offline') {
        return 1;
      } else if (b.presence === 'online' && a.presence === 'offline') {
        return -1;
      } else {
        return 0;
      }
    })

return newArray;
}

#9


0  

Try This:

试试这个:

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

var statusOrder = ["online", "offline"];

objs = objs.sort(function(a, b) { 
     return statusOrder.indexOf(a.presence) - statusOrder.indexOf(b.presence);
 });

Even shorter with ECMAScript6:

与ECMAScript6更短:

objs = objs.sort((a, b) => statusOrder.indexOf(a.presence) - statusOrder.indexOf(b.presence));

Answer taken from Faly's answer to another post.

答案取自Faly的另一个帖子。

#10


0  

@Oj Obasi, try the below code.

@Oj Obasi,试试下面的代码。

It uses map() method defined on arrays.

它使用在数组上定义的map()方法。

    var objs = [ 
        { id: 'X82ns', name: 'james', presence: 'online' },
        { id: '8YSHJ',    name: 'mary', presence: 'offline' },
        { id: '7XHSK', name: 'rene', presence: 'online' }
    ];

    /* Pretty printing objs array*/
    console.log(JSON.stringify(objs, null, 4))  // Before modification (sorting)
    /*
    [
        {
            "id": "X82ns",
            "name": "james",
            "presence": "online"
        },
        {
            "id": "8YSHJ",
            "name": "mary",
            "presence": "offline"
        },
        {
            "id": "7XHSK",
            "name": "rene",
            "presence": "online"
        }
    ]
    */

    objs.map((item, index) => { 
    	if(item.presence === 'online') { // online, add to front then remove this item from its current position
    		objs.splice(0, 0, item) // add at front
    	} else { // offline, push at end then remove this item from its current position
    		objs.splice(objs.length, 1, item) // push at end	
    	}
    	objs.splice(index, 1) // remove
    })

    /* Pretty printing objs array */
    console.log(JSON.stringify(objs, null, 4))  // After modification (sorting)
    /*
    [
        {
            "id": "X82ns",
            "name": "james",
            "presence": "online"
        },
        {
            "id": "7XHSK",
            "name": "rene",
            "presence": "online"
        },
        {
            "id": "8YSHJ",
            "name": "mary",
            "presence": "offline"
        }
    ]
    */

#1


6  

You can use localeCompare method.

您可以使用localeCompare方法。

var objs = [ { id: 'X82ns', name: 'james', presence: 'online' }, { id: '8YSHJ', name: 'mary', presence: 'offline' }, { id: '7XHSK', name: 'rene', presence: 'online' } ];

objs.sort((a,b) => b.presence.localeCompare(a.presence));
console.log(objs);

Don't forget that the sort() method sorts the elements of an array in place so you do not need to use const newArray = objs.sort....

别忘了sort()方法排序数组的元素,所以您不需要使用const newArray = objs.sort ....

#2


1  

Use sort function with condition of a.presence < b.presence because of online is bigger than offline (f and n)

使用具有a条件的排序函数。< b。线上的存在大于线下的存在(f和n)

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

objs.sort(function(a, b) {
  return a.presence < b.presence;
});

console.log(objs);

#3


1  

You could simply compare the String with >, = and <

可以将字符串与> =和 <进行比较< p>

let objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

let res = objs.sort((a,b) => a.presence > b.presence ? -1 : a.presence == b.presence ? 0 : 1);
console.log(res);

#4


1  

let objArr = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

let onlineArr = objArr.filter(x=>x.presence === 'online')
let offlineArr = objArr.filter(x=>x.presence === 'offline')
console.log([...onlineArr, ...offlineArr])

In terms of readability, you can split them into two array and using array destructuring to join them at last

在可读性方面,您可以将它们分割为两个数组,最后使用数组析构来连接它们

#5


1  

You could take an object with the order as values and sort by it. This allowes to use a default value for unknow values.

你可以取一个具有顺序的对象作为值并对其进行排序。这允许对未知值使用默认值。

var array = [{ id: 'X82ns', name: 'james', presence: 'online' }, { id: '8YSHJ', name: 'mary', presence: 'offline' }, { id: '7XHSK', name: 'rene', presence: 'online' }],
    order = { online: 1, offline: 2, default: Infinity };
    
array.sort((a, b) => (order[a.presence] || order.default) - (order[b.presence] || order.default));

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

#6


1  

Use the > sign to get online first and offline at the end. You can also create a separate function sortFn so this logic can be reused for multiple arrays.

使用>标志,首先在线,最后离线。您还可以创建一个单独的函数sortFn,以便可以为多个数组重用该逻辑。

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

function sortFn(a, b){
  return b.presence > a.presence;
}
objs.sort(sortFn);
console.log(objs);

#7


1  

You need to actually compare the items, and if they are now the same, then check for presence

您需要实际地比较这些项目,如果它们现在是相同的,那么检查是否存在

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

const newArray = objs.sort((a, b) => {
      if (a.presence !== b.presence) {
        return a.presence === "online" ? -1 : 1;
      }
      return 0;
});


console.log(newArray);

#8


1  

Try this:

试试这个:

const newArray = objs.sort((a, b) => {
      if (a.presence === 'online' && b.presence === 'offline') {
        return 1;
      } else if (b.presence === 'online' && a.presence === 'offline') {
        return -1;
      } else {
        return 0;
      }
    })

return newArray;
}

#9


0  

Try This:

试试这个:

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

var statusOrder = ["online", "offline"];

objs = objs.sort(function(a, b) { 
     return statusOrder.indexOf(a.presence) - statusOrder.indexOf(b.presence);
 });

Even shorter with ECMAScript6:

与ECMAScript6更短:

objs = objs.sort((a, b) => statusOrder.indexOf(a.presence) - statusOrder.indexOf(b.presence));

Answer taken from Faly's answer to another post.

答案取自Faly的另一个帖子。

#10


0  

@Oj Obasi, try the below code.

@Oj Obasi,试试下面的代码。

It uses map() method defined on arrays.

它使用在数组上定义的map()方法。

    var objs = [ 
        { id: 'X82ns', name: 'james', presence: 'online' },
        { id: '8YSHJ',    name: 'mary', presence: 'offline' },
        { id: '7XHSK', name: 'rene', presence: 'online' }
    ];

    /* Pretty printing objs array*/
    console.log(JSON.stringify(objs, null, 4))  // Before modification (sorting)
    /*
    [
        {
            "id": "X82ns",
            "name": "james",
            "presence": "online"
        },
        {
            "id": "8YSHJ",
            "name": "mary",
            "presence": "offline"
        },
        {
            "id": "7XHSK",
            "name": "rene",
            "presence": "online"
        }
    ]
    */

    objs.map((item, index) => { 
    	if(item.presence === 'online') { // online, add to front then remove this item from its current position
    		objs.splice(0, 0, item) // add at front
    	} else { // offline, push at end then remove this item from its current position
    		objs.splice(objs.length, 1, item) // push at end	
    	}
    	objs.splice(index, 1) // remove
    })

    /* Pretty printing objs array */
    console.log(JSON.stringify(objs, null, 4))  // After modification (sorting)
    /*
    [
        {
            "id": "X82ns",
            "name": "james",
            "presence": "online"
        },
        {
            "id": "7XHSK",
            "name": "rene",
            "presence": "online"
        },
        {
            "id": "8YSHJ",
            "name": "mary",
            "presence": "offline"
        }
    ]
    */