const data = [
{ name: "John", age: 25, type: "other" },
{ name: "Jane", age: 30, type: "other" },
{ name: "Bob", age: 20, type: "a" },
{ name: "Sue", age: 35, type: "b" },
{ name: "Tom", age: 25, type: "a" },
{ name: "Tim", age: 30, type: "b" },
{ name: "Ann", age: 20, type: "a" },
{ name: "Jim", age: 35, type: "b" },
]
function sortData(arr, sortKey1, sortKey2, otherValue) {
const sortedArray = arr.sort((a, b) => {
if (a[sortKey1] < b[sortKey1]) return -1
if (a[sortKey1] > b[sortKey1]) return 1
if (a[sortKey2] < b[sortKey2]) return -1
if (a[sortKey2] > b[sortKey2]) return 1
return 0
})
const otherIndex = sortedArray.findIndex((item) => item[sortKey1] === otherValue)
if (otherIndex >= 0) {
const otherItem = sortedArray.splice(otherIndex, 1)
sortedArray.push(...otherItem)
}
return sortedArray
}
const sortedData = sortData(data, "type", "age", "other")
console.log(sortedData)
以上示例中,我们定义了 sortData
函数,以及测试数据 data
。函数取三个参数:原始数组、第一个排序键、第二个排序键和带“其他”值的字符串。
函数中使用 JavaScript 的 sort
函数对原始数组进行排序,按照第一个和第二个键进行比较。最终找到带“其他”值的对象,并将其从排序后的数组中取出并添加到末尾。
最后,我们将排序后的结果保存在 sortedData
变量中并输出。
上一篇:按照两个键展开嵌套结构
下一篇:按照两个交替的列进行排序