本文介绍了Javascript基于字段值的任意排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个对象数组,如下所示:

So I have an array of object which looks like this:

var myArray = [{priority : "low"}, {priority: "critical"}, {priority: "high"}]

我需要排序这样:1)严重,2)高和3)低。

I need to sort in this way: 1)Critical, 2) High and 3) Low.

如何做到这一点?

推荐答案

我建议使用一个对象来存储排序顺序。

I suggest to use an object for the storing of the sort order.

如果需要一个默认值进行排序,您可以使用一个值来排序未知优先级以开始或结束。

If you need a default value for sorting, you could use a value for sorting unknown priority to start or to the end.

var sort = ['critical', 'high', 'low'],
    defaultValue = Infinity,
    sortObj = {},
    myArray = [{ priority: "unknown" }, { priority: "low" }, { priority: "critical" }, { priority: "high" }];

sort.forEach(function (a, i) { sortObj[a] = i + 1; });

myArray.sort(function (a, b) {
    return (sortObj[a.priority] || defaultValue) - (sortObj[b.priority] || defaultValue);
});
	
console.log(myArray);

这篇关于Javascript基于字段值的任意排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 09:20